Jump to content
Larry Ullman's Book Forums

How To Get Around Select Prepared Statements


Recommended Posts

I am searching around for many days to work with SELECT prepared statements. I can't figure out, how to handle the situation when the SELECT statement in a scenario does not return any result.

 

For example,

 

 

$q4 = "SELECT user_id, book_id from user_book_trn where user_id = {$_SESSION['user_id']} and book_id= ?";

//It is possible that this query returns 0 results. In this case, mysli_prepare stmt does not work (or returns FALSE). In simple querys, we used to check result with mysqli_num_rows(query result). Is there anything like that here? If the query runs right, then I want to display results, or else I need to insert a record in a table.

//Prepare the statement:

if($stmt4 = mysqli_prepare($dbc, $q4))

{

echo "Working for stmt4";

//bind variable to query's placeholder:

mysqli_stmt_bind_param($stmt4,'i', $mid);

 

//Execute query:

mysqli_stmt_execute($stmt4);

 

//Bind resutls:

mysqli_stmt_bind_result($stmt4, $uid, $bkid);

 

//fetch results:

mysqli_stmt_fetch($stmt4);

 

 

mysqli_stmt_store_result($stmt4);

 

if(mysqli_stmt_num_rows($stmt4) == 0) //The flow does not reach here, if the query fails to return rows.

//insert record.

}

Link to comment
Share on other sites

  • 2 weeks later...

Thank you very much, Dark Prince and Antonio for your replies. However, as php.net documentation, mysqli_affected_rows function only works with queries which update a table INSERT, UPDATE, or DELETE query.. In order to get the number of rows from a SELECT query, usemysqli_stmt_num_rows() instead.

 

http://php.net/manual/en/mysqli-stmt.affected-rows.php

 

I worked on mysqli_stmt_num_rows: Changed my code to remove //fetch results:

mysqli_stmt_fetch($stmt4)

so, my script is working as I intended it do. Still there may be better ways to do what I'm asking. Well, thanks again..

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...