我需要检查数据库中是否存在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.".";}
}
答案 0 :(得分: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.';
}
}
答案 1 :(得分:-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