删除行时出现SQL语法错误

时间:2014-02-21 20:50:01

标签: php mysql

好的,所以我基本上有一个HTML表单,其中包含一个隐藏的输入和一个提交按钮。按下按钮时,它将删除MySQL表中的特定行。代码实际上都是它应该执行的功能。但是,当我运行它时,我不断显示语法错误。一旦我收到错误,如果我回去就行了,这就是我想要的。我只是不确定如何在运行之后使其重定向,而不是得到错误。

错误:

错误:您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行的“1”附近使用正确的语法

第1行对我来说似乎很好(因此混乱)。

正在运行的PHP代码(campaignPostDelete.php):

<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$postID = $_POST['postID'];

$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=" . $postID);

if (!mysqli_query($con,$delete))
  {
  die('Error: ' . mysqli_error($con));
  }

header("Location: index.php");
die();

mysqli_close($con);
?>

使用PHP的HTML表单,以备不时之需:

<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$campaignID = $_SESSION['campaignID'];


$result = mysqli_query($con,"SELECT posts.postID, posts.postDate, posts.postName, posts.postEntry FROM posts 
   INNER JOIN campaigns ON posts.campaignID= $campaignID
         AND posts.campaignID= campaigns.campaignID ORDER BY postDate desc");

while($row = mysqli_fetch_array($result))
  {
  echo "<div id='campaignPostContainer'>";
  echo "<ul class='campaignPostBox'>";
  echo "<p class='postInfo'>";
  echo "<form name='postDelete' action='campaignPostDelete.php' method='post'>
            <input type='hidden' name='postID' value=" . $row['postID'] . ">
            <input type='submit'>
        </form>";
  echo "Posted on:";
  echo "<li>" . $row['postDate'] . "</li>";
  echo "</p>";
  echo "<p class='postInfo'>";
  echo "Posted by:";
  echo "<li>" . $row['postName'] . "</li>";
  echo "</p>";
  echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
  echo "</ul>";
  echo "</div>";
  echo "<hr>";
  }


mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:2)

您将ID用单引号括起来。它是一个整数,所以不应该用引号括起来。

$delete = mysqli_query($con,"DELETE FROM posts WHERE postID='$postID'");

应该是:

$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=$postID");

但是,您也将连接字符串传递两次。所以请这样做:

$delete = "DELETE FROM posts WHERE postID=$postID";

if (!mysqli_query($con, $delete))
{
  die('Error: ' . mysqli_error($con));
}

但这仍然让您容易受到SQL注入攻击。 至少这样可以改善整体效果:

$delete = sprintf("DELETE FROM posts WHERE postID=%s", mysql_real_escape_string($postID));

if (!mysqli_query($con, $delete))
{
  die('Error: ' . mysqli_error($con));
}

您还希望对其他输入进行消毒。