检查记录是否存在

检查记录是否存在

本文介绍了检查记录是否存在(PDO)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查数据库中是否存在记录,但是当我运行下面的代码时,我得到的只是确认数据库连接的消息.解析代码后,我没有收到两条消息中的任何一条.我是PDO的新手,并尝试了各种方法来完成这项工作,但仍然没有结果.有人可以帮忙吗?

I am trying to check if a record exists in a database, but when I run the code below, all I get is the message confirming a database connection. I do not get either of the two messages after parsing the code. I am new to PDO and tried all kinds of ways to make this work but still get no result. Can anyone help please?

<?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".

A few things. MySQL does not use the == equality operator, instead you should just use =. In addition, since you're using PDO, it might be better to set up Prepared Statements.

最后,由于您使用COUNT(*),因此您的查询将始终返回1条记录.您需要按以下方式更新代码:

Finally, since you use COUNT(*), your query will always return 1 record. You need to update your code as follows:

$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语句:

It's probably worth noting too that since you're receiving $telephone direct from the $_GET super-global, you shouldn't really output it unsanitized to the browser (for reasons of XSS vulnerabilities). I'd recommend updating your first echo statement as follows:

echo 'The telephone number: ' . strip_tags($telephone). ' is already in the database<br />';

这篇关于检查记录是否存在(PDO)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 08:18