这个mysql / php是否正确删除一行?

时间:2011-05-08 19:16:33

标签: php mysql sql

<?php
$id = $_POST['dr'];
$dbhost = 'star***.***.edu';
$dbuser = '***4123';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = "DELETE FROM address
        WHERE idnum=\"".$id\"";

mysql_select_db('***4123');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>

所以只需要一些帮助来确定这是否语法正确。应该通过ajax发送的是我希望在表地址

中删除的行的id号

3 个答案:

答案 0 :(得分:3)

您的查询语法看起来不正确,尤其是因为您"的转义已完全关闭。同样,您应该在查询中使用单引号作为字符串分隔符,而不是您使用的双引号。

$sql = "DELETE FROM address WHERE idnum = " . $id;

这应该有效。这假设id是数字(即整数,浮点数,小数等)。您应该始终验证提供的数据,或至少在将数据带到数据库附近之前进行清理,否则有人可以轻松地SQL注入您的网站。应该提供的快速清理是将发布的值转换为int。

$id = (int) $_POST [ 'dr' ];

答案 1 :(得分:1)

使用PDO。更简单的错误处理和更好的数据清理方法:

<?php
  try {
    $db = new PDO ('mysql:host=star***.***.edu;dbname=***4123', '***4123', '*****');
  }

  catch (Exception $e)
  {
    die('Could not connect: ' . $e->getMessage());
  }

  $statement = $db->prepare('DELETE FROM address WHERE idnum=?');

  $statement->bindParam(1, $_POST['dr']);

  if (false === $statement->execute())
  {
    die('Could not delete data: ' . print_r($pdo->errorInfo(),true));
  }

PDO会自动关闭连接,因此无需再做任何事情。

答案 2 :(得分:-1)

<?php
$id = mysql_real_escape_string($_POST['dr']);
$dbhost = 'star***.***.edu';
$dbuser = '***4123';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = "DELETE FROM address
        WHERE idnum= '$id' ";

mysql_select_db('***4123');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>

尝试使用MySQLi,Prepared Statement并且永远不要相信输入