简体   繁体   English

我想按 id 删除行,但它不起作用 PHP 和 MYSQL

[英]I want to delete row by id, but it's not working PHP and MYSQL

Page that has delete button (searchvehicle.php).具有删除按钮的页面 (searchvehicle.php)。 Im returning the data using ajax.我使用 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 class="table-responsive">
        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
        <thead class="thead-light">
        <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'].'" class="btn btn-primary btn-sm">Update</a>
            <a  href="#myModal" class="btn btn-danger btn-sm" data-toggle="modal">Delete</a>
            <div id="myModal" class="modal fade">
            <div class="modal-dialog modal-confirm">
                <div class="modal-content">
                    <div class="modal-header flex-column">
                        <div class="icon-box">
                            <i class="material-icons">&#xE5CD;</i>
                        </div>                      
                        <h4 class="modal-title w-100">Are you sure?</h4>    
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                        <div class="modal-body">
                            <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 class="modal-footer justify-content-center">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                               
                            <a class="btn btn-danger" 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.这是 del.php 脚本。

<?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 js脚本

<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.我注意到 id 是根据编辑 id 固定的。 For example if id for edit is 2, the id for all delete button is 2 as well.例如,如果编辑的 id 为 2,则所有删除按钮的 id 也为 2。 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.非常感谢帮助:) Ps:我不确定这是不是因为代码在 ajax 的返回变量中。

You cannot repeat id attributes.您不能重复id属性。 You have duplicated modals with the same id="myModal" so presumably only the first one is selected to be shown.您有重复的具有相同id="myModal"的模式,因此大概只选择第一个显示。

I would suggest something like我会建议像

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

There are also serious problems with deleting records via GET request (think of what a web crawler could do).通过 GET 请求删除记录也存在严重问题(想想 web 爬虫可以做什么)。 I would recommend a DELETE request instead.我建议改用 DELETE 请求。

<!-- replace the <a> tag -->
<button
  type="button"
  class="btn btn-danger"
  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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM