-1

I can't seem to figure out what's wrong with this PHP code:

$sql = $db->prepare("SELECT EXISTS(SELECT 1 FROM profile WHERE uid = ?)");  
          $p_already_exists = $sql->execute([$_SESSION['uid']]);

I'm running the sqlite3 PDO module, and it doesn't matter whether the 'uid' is in the database or not, $p_already_exists is always assigned 1. I'm expecting for it to be 0 if it's not in the database, and 1 if there is at least one record in the database.

I've double checked that echoing out $_SESSION['uid'] gives me the same value to uid (TEXT) in the database.

Does anybody know why this isn't working for me? At the end of the day I'm just after an efficient way of returning a boolean value (hence why I'm not using COUNT). Appreciate your help.

ref How to check whether SELECT EXISTS returns a value or not?

sharkbites
  • 101
  • 1
  • 8
  • 1
    You are looking at the return value of the `execute` method - and that does not have anything to do with whether the statement found anything or not, that _only_ reflects whether the statement could execute successfully and without errors. – CBroe Jun 23 '20 at 09:38

1 Answers1

1

PDOStatement::execute() returns a boolean value, TRUE on success or FALSE on failure:

https://www.php.net/manual/en/pdostatement.execute.php

If you want to get the actual result returned by the SQL statement execution, rather than the status of the execution itself, you should use one of the fetch* functions, for example fetchColumn(), after calling execute().

Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25