此示例删除代码不会从数据库中删除项目

时间:2016-04-21 02:52:53

标签: php mysqli

这是我创建的删除代码MySQL数据库的示例删除代码。当我执行此代码时,显示成功的消息,但条目不会从数据库中删除。记录将跟踪“事件”中的主键。表' id'

<?php
    require 'dbconnect.php';
    session_start();
    $id=$_SESSION['id'];
    $id = "0";

    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }

    if ( !empty($_POST)) {
        // keep track post values
        $id = $_POST['id'];

        // delete data


        $sql="DELETE * FROM events WHERE events.id='$id'"; //mysqli query
        $result=mysqli_query($conn,$sql); //connection string and mysqli query variable


    if($result==true)
            {
    echo "<script type='text/javascript'>alert('successfully DELETED!')</script>"; // javascript message for Successful delete
    echo "<script>setTimeout(\"location.href = 'list_events.php';\",15);</script>"; // return page

            }
            else
            {
    echo "<script type='text/javascript'>alert('failed to DELETE RETRY!')</script>"; //failed to delete message
    echo "<script>setTimeout(\"location.href = 'list_events.php';\",15);</script>"; //return page
            }
            header("Location: list_events.php"); // header page

        }
    ?>

2 个答案:

答案 0 :(得分:1)

您可以使用此

$sql="DELETE FROM events WHERE events.id='{$id}'"; //mysqli query

为了安全起见。 检查你是否在$ id中获得了一些值,它也存在于数据库中。

答案 1 :(得分:0)

使用DELETE FROM而不是DELETE * FROM,您可以使用以下命令来提高安全性:

$sql="DELETE FROM events WHERE events.id=?"; 
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('d',$id);
/* execute prepared statement */
$result = $stmt->execute();