sonal Posted January 11, 2012 Share Posted January 11, 2012 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 More sharing options...
Antonio Conte Posted January 11, 2012 Share Posted January 11, 2012 mysqli_affected_rows($stmt4); Try that. 1 Link to comment Share on other sites More sharing options...
Dark Prince Posted January 21, 2012 Share Posted January 21, 2012 to add to antonio's reply if (mysqli_affected_rows($stmt4) => 1)) // if there is 1 or more records affected it will return true. { // what to do here } if you want to check if there is no affected rows just change to == 0 Link to comment Share on other sites More sharing options...
sonal Posted January 22, 2012 Author Share Posted January 22, 2012 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.. 1 Link to comment Share on other sites More sharing options...
HartleySan Posted January 27, 2012 Share Posted January 27, 2012 Larry's Ecommerce book explains how to used prepared statements. 1 Link to comment Share on other sites More sharing options...
Recommended Posts