PHP脚本无法删除SQL记录

时间:2018-02-02 13:59:28

标签: php html mysql sql

目前我有一个外部php脚本试图从博客表中删除一行,这应该通过post方法拉出的id变量来完成。目前的代码:

    <?php
include 'dbconnection.php';

$id = $_POST['id'];

$query = "DELETE FROM 'blog' WHERE id = $id";

if(mysqli_query($conn, $query)){
    header("location: adminDeleteComplete.php");
} else {
    header("location: adminDeleteFailed.php");
}


?>

HTML部分:

<form method="post" action="adminDeleter.php">
    <input type="text" name="id" placeholder="ID" value="<?php echo $id ?>">
    <input type="text" name="title" placeholder="Title" value="<?php echo $title ?>">
    <input type="text" name="subtitle" placeholder="Subtitle" value="<?php echo $subtitle ?>" required>                
    <textarea type="text" name="message" required><?php echo $content ?></textarea>
    <button class="SUB">Delete Post!</button>
</form>

任何人都可以解释我做错了什么吗?我理解并完成了博客网站的添加和更新部分,但由于一些奇怪的原因,它不会被删除?

1 个答案:

答案 0 :(得分:-1)

尝试使用预准备语句,因为它可以防止针对SQL注入的攻击。<​​/ p>

我在页面顶部添加了连接变量。您可以将这些内容添加到dbconnection.php文件中,并将其与原始帖子一样包含在顶部。

 <?php

 //add your own details
 $servername = "";
 $username = "";
 $password = "";
 $dbname = "";


$id = $_POST['id'];

try {

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters
$stmt = $conn->prepare("DELETE

                        FROM

                        blog 

                        WHERE 

                        id = :id

                       ");

//binding the :id with your $id variable from the POST
$stmt->execute(array(':id' => $id ) );

//if successfull
header("location: adminDeleteComplete.php");

} catch(PDOException $e) {

//error handling
header("location: adminDeleteFailed.php");

echo "Error: " . $e->getMessage();

}

$conn = null;

?>