Home > Software engineering >  I want to delete row by id, but it's not working PHP and MYSQL
I want to delete row by id, but it's not working PHP and MYSQL

Time:01-04

Page that has delete button (searchvehicle.php). Im returning the data using ajax.

<?php
session_start(); 
require ('../db.php');
$id = $_SESSION['id'];

$return = '';

if(isset($_POST["query"]))
{
    $search = mysqli_real_escape_string($connection, $_POST["query"]);
    $query = "SELECT vehicle.id, vehicle.vehicle_no, color, model, type, vehicle.comp_id, vehicle.user_id, company.comp_name  
    FROM vehicle
    LEFT JOIN company 
    ON vehicle.comp_id = company.id 
    WHERE vehicle.id  LIKE '%".$search."%'
    OR vehicle_no LIKE '%".$search."%' 
    OR vehicle.comp_id LIKE '%".$search."%'
    AND FIND_IN_SET( vehicle.comp_id, '".$userprofile['company_id']."' )
    AND vehicle.user_id = '".$id."'
    ";}
else
{
    $query = "SELECT vehicle.id, vehicle.vehicle_no, color, model, type, vehicle.comp_id, vehicle.user_id, company.comp_name  
    FROM vehicle  
    LEFT JOIN company 
    ON vehicle.comp_id = company.id 
    WHERE FIND_IN_SET( vehicle.comp_id, '".$userprofile['company_id']."' )
    AND vehicle.user_id = '".$id."'
    ";
}

$result = mysqli_query($connection, $query);
$i = 1;

    if(mysqli_num_rows($result) > 0)
    {
        $return .='
        
        <div >
        <table  id="dataTable" width="100%" cellspacing="0">
        <thead >
        <tr>
            <th>ID</th>
            <th>Vehicle Num</th>
            <th>Color</th>
            <th>Model</th>
            <th>Type</th>
            <th>Company Num</th>
            <th>Company Name</th>
            <th>Action</th>
        </tr>';
        while($row1 = mysqli_fetch_array($result))
        {
            if($row1['user_id'] == $id)
            {
                $return .= '
            <tr>
            <td>'.$i  .'</td>
            <td>'.$row1["vehicle_no"].'</td>
            <td>'.$row1["color"].'</td>
            <td>'.$row1["model"].'</td>
            <td>'.$row1["type"].'</td>
            <td>'.$row1["comp_id"].'</td>
            <td>'.$row1["comp_name"].'</td>
            
            <td>
            <a href="editvehicle.php?id='.$row1['id'].'" >Update</a>
            <a  href="#myModal"  data-toggle="modal">Delete</a>
            <div id="myModal" >
            <div >
                <div >
                    <div >
                        <div >
                            <i >&#xE5CD;</i>
                        </div>                      
                        <h4 >Are you sure?</h4>    
                        <button type="button"  data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                        <div >
                            <p>Do you really want to delete these records? All activity related to the driver will also be deleted. This process cannot be undone.</p>
                        </div>
                        <div >
                            <button type="button"  data-dismiss="modal">Cancel</button>
                               
                            <a  href="del.php?id='.$row1['id'].'">Delete</a>
                        </div>
                </div>
            </div>
        </div>     
            </td>

            </tr>
            </thead>';
            }
            else
            {
            
            }
            
        }
        echo $return;
        }
    else
    {
        echo 'No results containing all your search terms were found.';
    }

    
?>

This the del.php script.

<?php

$id = $_GET['id'];
$del_veh = "DELETE FROM vehicle WHERE id='$id' ";
$run_del_veh = mysqli_query($connection, $del_veh);

if($run_del_veh > 0)
{
    
    header("Location:/vehicle/listvehicle.php");
    exit(0);
}
else
{
   
}
?>

js script

<script>
$(document).ready(function(){
    load_data();
    function load_data(query)
    {
        $.ajax({
        url:"searchvehicle.php",
        method:"POST",
        data:{query:query},
        success:function(data)
        {
            $('#result').html(data);
        }
        });
    }
    $('#search').keyup(function(){
    var search = $(this).val();
    if(search != '')
    {
        load_data(search);
    }
    else
    {
        load_data();
    }
    });
});
</script>

I notice that the id is fixed according to edit id. For example if id for edit is 2, the id for all delete button is 2 as well. How can I fix the problem? Help is much appreciated :) Ps: I'm not sure if this is because the code is in return variable for ajax.

CodePudding user response:

You cannot repeat id attributes. You have duplicated modals with the same id="myModal" so presumably only the first one is selected to be shown.

I would suggest something like

<a
  href="#myModal-'.$row1['id'].'"
  
  data-toggle="modal"
>Delete</a>
<div id="myModal-'.$row1['id'].'" >

There are also serious problems with deleting records via GET request (think of what a web crawler could do). I would recommend a DELETE request instead.

<!-- replace the <a> tag -->
<button
  type="button"
  
  data-delete="'.$row1['id'].'"
>Delete</button>
$(document).on("click", "button[data-delete]", (e) => {
  e.preventDefault();
  $.ajax({
    url: `del.php?id=${e.target.dataset.delete}`,
    method: "DELETE",
  })
    .done(() => {
      window.location = "/vehicle/listvehicle.php";
    })
    .fail(console.error);
});
<?php
// del.php
if ($_SERVER['REQUEST_METHOD'] !== 'DELETE') {
    http_response_code(405);
    exit;
}

$stmt = $connection->prepare('DELETE FROM vehicle WHERE id = ?');
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();

if ($stmt->affected_rows === 0) {
    http_response_code(404);
}
  • Related