检查PHP是否存在SQL行

时间:2011-07-08 04:34:38

标签: php sql database if-statement

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

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

3 个答案:

答案 0 :(得分:25)

如果您使用的是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.
}

如果您想像alex建议的那样使用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.
}

答案 1 :(得分:11)

Sayem的答案有最多的赞成,但我认为这对于PDO是不正确的。

来自PHP docs

对于大多数数据库,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;

答案 2 :(得分:4)

另一种方法

$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
}