1

Ok, so I have the following query to check if a row exists:

$stmt = $mysqli->prepare("SELECT EXISTS(SELECT 1 FROM tb WHERE x = ? LIMIT 1)");
$stmt->bind_param("i", $y);
$stmt->execute();
$stmt->store_result();

How would I check the response of this to see if it was successful? There are lots of examples saying that this is the best way to check if a row exists, but no examples showing it in use with a prepared statement. (Ref: Best way to test if a row exists in a MySQL table)

I'd normally use:

if ($stmt->affected_rows > 0) {
    //Success
}

But it doesn't apply in this case.

Any ideas?

Community
  • 1
  • 1

1 Answers1

3

As commented by Gordon, your query will return exactly 1 value, which will be either a 1 or 0. Also, a LIMIT is unnecessary inside of an EXISTS query.

$stmt = $mysqli->prepare("SELECT EXISTS(SELECT 1 FROM tb WHERE x = ?)");
$stmt->bind_param("i", $y);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();

if($exists) {

}
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85