php - How can I simply determine if there is (not) a result from PDOStatement fetch? -


consider following code:

$conn = new pdo("connection string", "user name", "password"); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception);  $sql = "select `id` `users` `displayname` = :displayname"; $parms = array(':displayname' => 'test'); $stmt = $conn->prepare($sql, array(pdo::attr_cursor => pdo::cursor_fwdonly)); $stmt->execute($parms);  $res = $stmt->fetch(); echo $res == null; 

and more consider line: echo ($res == null);

if there no row in database matches echo displays value of 1 -as expected -because $res in fact null. however, if there result returned $stmt->fetch(); echo produces nothing. but, have expected have produced 0 because value of $res array.

how can consistently , concisely compare result simply determine if there result or not?

when there's no result, doesn't return null. returns false (well, assuming pdo::fetch_both -- see full list, read doc). also, false casted string empty string. that's why you're not getting output.

echo false; //outputs nothing  $s = (string) false; var_dump($s === ""); //true  

as determining whether or not have result, can simple implicit check:

$res = $stmt->fetch(); if ($res) {      echo 'got row!'; } else {     echo 'no row :('; } 

this works because of few implicit casts. consider fetch going return: either non-empty array, or false. (bool) $arr === true if count($arr) > 0. here, should able see why works.

(note: in theory, result set indeed empty row. cause fetch return emtpy array. break implicit comparison considered false. can't imagine ever happen though. can't think of statement return result set row has no columns.)


Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -