Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if SQL row exists with PHP

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
}
like image 557
John Avatar asked Jul 08 '11 04:07

John


People also ask

How do you check if data exists in a table php?

To check whether a particular value exists in the database, you simply have to run just a regular SELECT query, fetch a row and see whether anything has been fetched. Here we are selecting a row matching our criteria, then fetching it and then checking whether anything has been selected or not.

How do you check if a record exists in a MySQL database php?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do you check if data exists in a table SQL?

The SQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


2 Answers

If you would like to use PDO (PHP Data Object), 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.
}
like image 126
MD Sayem Ahmed Avatar answered Sep 22 '22 08:09

MD Sayem Ahmed


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;
like image 26
rvr_jon Avatar answered Sep 22 '22 08:09

rvr_jon