harsh sharma harsh sharma - 11 days ago 4
MySQL Question

Deleting data by clicking DELETE button which is in table heading

I am fetching 10 records in table, now i have one table column heading named DELETE, below which there are checkboxes now i want to delete checked records on single click of that DELETE button.Pls tell how to do it in php codeigniter

<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Car</td>
<td>Address</td>
<td>Phone Number</td>
<td><a href="<?php echo site_url('User1/delete/'); ?>">Delete</td>
<td>Action </td>
</tr>

<?php foreach($posts as $a){ ?>
<tr>
<td><?php echo $a->id;?></td>
<td><?php echo $a->name;?></td>
<td><?php echo $a->car;?></td>
<td><?php echo $a->address;?></td>
<td><?php echo $a->cell_number;?></td>
<td>
<input type="checkbox" name="id" value="$a->id"><br>
</td>
</tr>
<?php }?>
</table>


Controller Code

function delete($id){
$result = $this->User_model->deletebyid($id);
if($result==true)
return true;
}


Model Code

function deletebyid($id){
$this->db->where('id', $id);
$this->db->delete('user_table');
if ($this->db->affected_rows() > 0) {
return true;
}else {
return false;
}
}


Getting this error

A Database Error Occurred

Error Number: 1054

Unknown column 'Array' in 'where clause'

DELETE FROM `user_table` WHERE `id` = `Array`

Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

Line Number: 691

Answer
<form method='post' action='<?php echo site_url('User1/delete/'); ?>' >
<table>
     <tr>
            <td>Id</td>  
            <td>Name</td>  
            <td>Car</td>  
            <td>Address</td>  
            <td>Phone Number</td> 
            <td><input type="submit" name="delete" value="Delete" /></td>          
            <td>Action </td>    
    </tr>

     <?php foreach($posts as $a){  ?>
     <tr>
            <td><?php echo $a->id;?></td>  
            <td><?php echo $a->name;?></td>  
            <td><?php echo $a->car;?></td>  
            <td><?php echo $a->address;?></td>  
            <td><?php echo $a->cell_number;?></td>  
            <td>
            <input type="checkbox" name="r_id[]" value="<?php echo $a->id; ?>"><br>
            </td>
      </tr>    
     <?php }?>  
   </table>  
</form>

Controller:

function delete($id){
echo "<pre>";print_r($_POST['r_id']);exit; // you will get all selected check box values. (which are the record ids. You just send this ids to model and delete them using sql IN operator [ex: id IN ('') ].
...
...
...
            }
Comments