我试图检查数据库中是否存在记录,但当我运行下面的代码时,我得到的只是确认数据库连接的消息。解析代码后,我没有得到这两条消息中的任何一条。我是PDO的新手,尝试了各种方法来实现这一点,但仍然没有结果。有人能帮忙吗?
<?php
$telephone= ($_GET [ 'telephone' ]);
try {
$dbh = new PDO("mysql:host=$hostname;dbname=gosdirect", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
$sql = "SELECT COUNT(*) FROM directory WHERE telephone == $telephone";
if ($res = $dbh->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
echo 'The telephone number: ' . $telephone. ' is already in the database<br />';
}
/* No rows matched -- do something else */
else {
echo 'No rows matched the query.';
}
}
$res = null;
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
一些事情。MySQL不使用==
相等运算符,而应该只使用=
。此外,由于您使用的是PDO,因此最好设置Prepared Statements。
最后,由于您使用COUNT(*)
,因此您的查询将始终返回1条记录。你需要更新你的代码如下:
$sql = $dbh->prepare("SELECT COUNT(*) AS `total` FROM directory WHERE telephone = :phone");
$sql->execute(array(':phone' => $telephone));
$result = $sql->fetchObject();
if ($result->total > 0)
{
echo 'The telephone number: ' . $telephone. ' is already in the database<br />';
}
else
{
echo 'No rows matched the query.';
}
可能还值得注意的是,由于您直接从$_GET
超级全局接收$telephone
,因此不应该将其未初始化地输出到浏览器(由于XSS漏洞的原因)。我建议更新您的第一个echo
声明如下:
echo 'The telephone number: ' . strip_tags($telephone). ' is already in the database<br />';
中不需要==
$sql = "SELECT COUNT(*) FROM directory WHERE telephone == $telephone";
应该是
$sql = "SELECT COUNT(*) FROM directory WHERE telephone = $telephone";
希望它能帮助
类似的东西(没有SQL注入;):
$sql = 'SELECT COUNT(*) FROM directory WHERE telephone = :phone';
$stmt = $conn->prepare($sql);
$sth->bindParam(':phone', $_GET['telephone'], PDO::PARAM_STR, 12);
$stmt->execute();
if($stmt->fetchColumn()) die('found');