使用 PHP 检查 SQL 行是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6620019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:52:47  来源:igfitidea点击:

check if SQL row exists with PHP

phpsqldatabaseif-statement

提问by John

I'm using MySQL with PHP and I need to do something like this (pseudocode):

我在 PHP 中使用 MySQL,我需要做这样的事情(伪代码):

if (sql row exists where username='bob')
{
    // do this stuff
}

回答by MD Sayem Ahmed

If you are using mysql database, then use the following -

如果您使用的是 mysql 数据库,请使用以下命令 -

$query = "SELECT username from my_table where username='bob'";
$result = mysql_query($query);

if(mysql_num_rows($result) > 0)
{
    // row exists. do whatever you would like to do.
}

If you would like to use PDO (PHP Data Object), as alex suggested, then use the following code -

如果您想PDO (PHP Data Object)按照亚历克斯的建议使用,请使用以下代码 -

$dbh = new PDO("mysql:host=your_host_name;dbname=your_db_name", $user, $pass);
$stmt = $dbh->prepare("SELECT username from my_table where username = ':name'");
$stmt->bindParam(":name", "bob");
$stmt->execute();

if($stmt->rowCount() > 0)
{
    // row exists. do whatever you want to do.
}

回答by rvr_jon

Sayem's answer has the most upvotes, but I believe it is incorrect regarding PDO.

Sayem 的回答获得了最多的赞成票,但我认为关于 PDO 是不正确的。

From the PHP docs:

来自PHP 文档

For most databases, PDOStatement::rowCount() does not return the number of rows affectedby a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned.

对于大多数数据库, PDOStatement::rowCount()不返回受SELECT 语句影响的行数。相反,使用 PDO::query() 发出一个 SELECT COUNT(*) 语句,其谓词与您预期的 SELECT 语句相同,然后使用 PDOStatement::fetchColumn() 来检索将返回的行数。

$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

  /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

       /* Issue the real SELECT statement and work with the results */
       $sql = "SELECT name FROM fruit WHERE calories > 100";
       foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
       }
  }
  /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
  }
}

$res = null;
$conn = null;

回答by Ilia Choly

another approach

另一种方法

$user = "bob";
$user = mysql_real_escape_string($user);
$result = mysql_query("SELECT COUNT(*) AS num_rows FROM my_table WHERE username='{$user}' LIMIT 1;");
$row = mysql_fetch_array($result);
if($row["num_rows"] > 0){
   //user exists
}