0

我需要检查数据库中是否存在 ID,以便删除它,如果不存在则显示消息警告。将“x”与“xtrue”进行比较时出现问题。

$x = $_REQUEST['X'];
$y = $_REQUEST['Y'];
if($x != "") {
    $xtrue = " SELECT x
                FROM ".$y."
                WHERE x=".$x;

    if($x == $xtrue) {
        $query="DELETE FROM ".$y." WHERE id=".$x;

        $recordset = mysql_query($query,$conn);

        echo "-> ".$x." from ".$y." deleted.";
        }
    else{echo "There is no ".$x." from ".$y.".";}
}
4

2 回答 2

1

你真的不应该使用mysql_*(因为 PHP5.5.0 它已被弃用)但如果你必须下面是如何做到这一点的示例。

您不需要检查记录是否存在,只需尝试将其删除并用于mysql_affected_rows确定是否删除了任何记录。

$x = $_REQUEST['x'];
$y = $_REQUEST['y'];

// Basic validation
// $x must be integer and $y may contains only letters and underscore
if (preg_match('/^[0-9]+$/', $x) and preg_match('/^[_a-z]+$/', $y)) {

    // If record is not exists it will not be removed
    mysql_query("DELETE FROM $y WHERE id = $x");

    if (mysql_affected_rows() == 1) {
        echo 'Record was deleted';
    } else {
        echo 'Record not exists.';
    }
}
于 2013-10-06T09:08:03.757 回答
-1
$x = $_REQUEST['X'];
$y = $_REQUEST['Y'];
/*Validation*/
if($x!="" && preg_match('/^[0-9]+$/', $x) && preg_match('/^[_a-z]+$/', $y)){
 $sql = $dbh->prepare("SELECT x FROM ? WHERE x=?");
 $sql->execute(array($y,$x));
 if($sql->rowCount() > 0) {
  $query=$dbh->prepare("DELETE FROM ? WHERE id=?");
  $query->execute(array($y,$x));
  echo "-> ".$x." from ".$y." deleted.";
 }else{
  echo "There is no ".$x." from ".$y.".";
}

更多关于 PDO 的信息:php.net/manual/en/book.pdo.php

于 2013-10-06T07:38:37.773 回答