.
Divya
In this example we will discuss about how to delete a record or data from MySQL database using CakePHP framework PHP.
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value
Notice : The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
The students table look like this:
id | first name | last name | City name | Email Id | Action |
---|---|---|---|---|---|
1 | Divyasundar | Sahu | Mumbai | divyasundar@gmail.com | Delete |
2 | Hritika | Sahu | Pune | hritika@gmail.com | Delete |
3 | Milan | Jena | Chennai | milanjena@gmail.com | Delete |
Now i am going to delete the id=3 record.
For delete record we use 4 file here
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/users/delete', ['controller' => 'Users', 'action' => 'delete']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
class UsersController extends AppController{
public function index(){
$users = TableRegistry::get('users');
$query = $users->find();
$this->set('results',$query);
}
public function delete($id){
$users_table = TableRegistry::get('users');
$users = $users_table->get($id);
$users_table->delete($users);
echo "User deleted successfully.";
$this->setAction('index');
}
}
?>
Now just create an empty View file under Users directory called delete.ctp.
<!DOCTYPE html>
<html>
<body>
<table border="1">
<thead>
<th>Id</th>
<th>First name</th>
<th>Last name</th>
<th>City name</th>
<th>Email</th>
<th>Action</th>
</thead>
<tbody>
<?php
foreach($this->a->fetchtable() as $row)
{
?>
<tr>
<td><?php echo $row->id ; ?></td>
<td><?php echo $row->first_name; ?></td>
<td><?php echo $row->last_name; ?></td>
<td><?php echo $row->city_name; ?></td>
<td><?php
$id=$row->id;
echo $row->email; ?></td>
<td><a href=<?php echo site_url('student_delete/deletedata/'.$id);?>>Delete</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
After delete the record the table look like this.
id | first name | last name | City name | Email Id | Action |
---|---|---|---|---|---|
1 | Divyasundar | Sahu | Mumbai | divyasundar@gmail.com | Delete |
2 | Hritika | Sahu | Pune | hritika@gmail.com | Delete |
.