javascript - 使用 PHP 和 JavaScript 从数据库中删除数据

标签 javascript php mysql database window.location

我正在处理 PHP 文件。我正在尝试制作一个表格来显示数据库中的产品列表。还有一个用于删除任何产品的按钮。我使用 javascript 从数据库中删除产品。我已经写了代码,没有发现任何错误。当我单击删除按钮时,它会显示确认框,但不会删除产品。这是代码:

<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("grocery_shop",$con);

error_reporting(E_ALL^E_NOTICE);
session_start();


    $sql = mysql_query("select * from products");


if($_GET['did']){
    mysql_query("delete from products where product_id='$_GET[did]'");
    header("Location: product.php");
}

?>
<table border="1px" style="width:100%">
    <tr>
    <th>Serial No</th>
    <th>Product Name</th>       
    <th>Product Type</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>Delete Product</th>
  </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>

    <?php
    $i=1;
    while ($u = mysql_fetch_array($sql)) {
        ?>
        <tr>
            <td><?php echo $i; ?></td>
            <td><?php echo $u['product_name'];?></td>
            <td><?php echo $u['product_type'];?></td>
            <td><?php echo $u['quantity'];?></td>
            <td><?php echo $u['price'];?></td>
            <td><?php echo "<a href=\"javascript:delproduct(id=$u[product_id])\">Delete</a>";?></td>

        </tr>
        <?php
    $i++;
    }
    ?>

    <script>
    function delproduct(id){
        var msg = confirm("Are you sure you want to delete this product?");

    if (msg) {
        window.location = "product.php?did="+product_id;
    }
    }
    </script>
</table>

最佳答案

问题出在您的 JavaScript 中,product_id 不存在

   if (msg) {
        window.location = "product.php?did="+id;
    }

出于调试目的,请尝试将其替换为您的代码,并让我们知道您收到的错误消息。

if($_GET['did']){
    mysql_query("delete from products where product_id='".$_GET['did']."'");
    echo "delete from products where product_id='".$_GET['did']."'";
    echo mysql_errno() . ": " . mysql_error() ;    
    die();
    //header("Location: product.php");
}

此外,还尝试在不带单引号的情况下运行查询,我假设product_id是一个整数。

so mysql_query("从产品中删除product_id=".$_GET['did']);

关于javascript - 使用 PHP 和 JavaScript 从数据库中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597464/

相关文章:

javascript - React - onChange 事件中的 setInterval

javascript - 在没有 node.js 的情况下使用 Javascript 库,例如 Cheerio

javascript - Joi 验证 - 如何根据输入使字段可选

php - 如何在 php-opencloud 中正确提取存档文件

仅当通过 Bash 脚本运行时 Mysql 才会出错

Javascript全局变量简单解决方案

php - 无法在写入上下文中使用函数返回值 Laravel 4

php - 使用 Laravel 的 ORM Eloquent 通过多个数据透视表查询对象

c# - 使用 EF 使用 sum 进行慢速 mysql 查询

MySQL 语法。表名、点、字段名之间可以使用空格吗?