check if SQL row exists with PHP

后端 未结 3 801
时光取名叫无心
时光取名叫无心 2020-12-05 15:25

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

if (sql row exists where username=\'bob\')
{
    // do this stuff
}
相关标签:
3条回答
  • 2020-12-05 15:49

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

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

    $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.
    }
    
    0 讨论(0)
  • 2020-12-05 15:59

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

    From the PHP docs:

    For most databases, PDOStatement::rowCount() does not return the number of rows affected by 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.

    $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;
    
    0 讨论(0)
  • 2020-12-05 16:06

    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
    }
    
    0 讨论(0)
提交回复
热议问题