Jump to content

How to check if stmt->execute() returns false


Fmdpa

Recommended Posts

I prefer using the mysqli stmts because of the bind_param function. But the only reason I don't use it all the time is because I haven't found a way to check if the execute() encounters errors. Normally I'd use something like:

$result =$db->query($sql);if (!$result) {//there was an error}

But I can't place the $stmt->execute() into a variable because of object incompatibilities or something. What is a good way to do this?

Link to comment
Share on other sites

I typically don't check if the execute method failed (bad practice, i know), but maybe you could try something like this:

$stmt->execute();if($stmt->errno){   //this code will execute if there was an error}

This checks the errno property of the mysqli class.http://www.php.net/manual/en/mysqli-stmt.errno.php

Link to comment
Share on other sites

That was unsuccessful. I did something like this:

$query="SELECT column1, column2 FROM `table` WHERE id=? LIMIT 1";$result=$con->prepare($query);$result->bind_param('s', $_GET['post_id']);$result->execute();$result->bind_result($col1, $col2);if ($result->errno) {header('location:error.php');}else {while ($result->fetch()) {$title = $col1;$post = $col2;}}

The problem was that the conditional with the $result->errno statement in it always returned false, whether the row existed or not.

Link to comment
Share on other sites

well according to the documentation in the link i sent you, $stmt->errno returns "An error code value. Zero means no error occurred.". oh oops, i guess my conditional logic was wrong. maybe it should be like this:

if($stmt->errno != 0) {//code to execute if there is an error}

Link to comment
Share on other sites

The problem is that $stmt->errno returns 0 whether the query is supposed to return true, or not.As you saw earlier, I am fetching data based on a $_GET variable. If "post_id=1" represents an existent post, errno will return 0. Great! But if I enter "post_id=12" (and there is not a row with an id of 12) then errno will again return 0...ok???

Link to comment
Share on other sites

oh so i think what you want is a property that returns how many results are returned. If you send the query a post_id that does not exist, there won't be an error. After you execute the query, you need to call the store_result() method and then check the num_rows property like this:

$stmt->store_result();printf("Number of rows: %d.\n", $stmt->num_rows);

Here is the documentation: http://www.php.net/manual/en/mysqli-stmt.num-rows.php

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...