简体   繁体   中英

Cleanest way to check if a record exists

I am using the following code to check if a row exists in my database:

$sql = "SELECT COUNT(1) FROM myTable WHERE user_id = :id_var";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id_var', $id_var);
$stmt->execute();

if ($stmt->fetch()[0]>0)
{
    //... many lines of code
}

All of the code works and the doubts I have are concerning if the previous code is clean and efficient or if there is room for improvement.

Currently there are two questions bugging me with my previous code:

  1. Should I have a LIMIT 1 at the end of my SQL statement? Does COUNT(1) already limit the amount of rows found by 1 or does the server keep searching for more records even after finding the first one?
  2. The if ($stmt->fetch()[0]>0) . Would this be the cleanest way to fetch the information from the SQL Query and execute the "if conditional"?

Of course if anyone spots anything else that can improve my code, I would love your feedback.

Q: Should I have a LIMIT 1 at the end of my SQL statement? Does COUNT(1) already limit the amount of rows found by 1 or does the server keep searching for more records even after finding the first one?

Your SELECT COUNT() FROM query will return one row, if the execution is successful, because there is no GROUP BY clause. There's no need to add a LIMIT 1 clause, it wouldn't have any affect.

The database will search for all rows that satisfy the conditions in the WHERE clause. If the user_id column is UNIQUE, and there is an index with that as the leading column, or, if that column is the PRIMARY KEY of the table... then the search for all matching rows will be efficient, using the index. If there isn't an index, then MySQL will need to search all the rows in the table.

It's the index that buys you good performance. You could write the query differently, to get a usable result. But what you have is fine.

Q: Is this the cleanest...

  if ($stmt->fetch()[0]>0)

My personal preference would be to avoid that construct, and break that up into two or more statements. The normal pattern...separate statement to fetch the row, and then do a test.

Personally, I would tend to avoid the COUNT() and just get a row, and test whether there was a row to fetch...

  $sql = "SELECT 1 AS `row_exists` FROM myTable WHERE user_id = :id_var";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(':id_var', $id_var);
  $stmt->execute();
  if($stmt->fetch())  {
      // row found
  } else {
      // row not found 
  }
  $stmt->closeCursor(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM