1

How can I check mysqli query if it returns boolean(false) or the result? If I try getting the num_rows I get php error because I'm trying to access a non object as object. But I need to check this because if its false I have to set a variable and if its not than get the result of the query.

my query looks like this:

<?php
$q = "SELECT `id` FROM `table` ORDER BY `id` DESC LIMIT 0, 1";
$res = mysqli->query($q);
?>
Laci K
  • 585
  • 2
  • 8
  • 24
  • Does this answer your question? [mysqli\_fetch\_assoc() expects parameter / Call to a member function bind\_param() errors. How to get the actual mysql error and fix it?](https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param) – Dharman Dec 29 '19 at 18:28

2 Answers2

2

You need to use === operator which also checks arguments type:

$q = "select ,....";
$res = $mysqli->query( $q );

if( $res !== false ) { 
   // query ok
} else {
   // query failed
}
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
1

To know if a variable is set to false, you can use

if($res === false){//strictly false, no 0 or ''
   //do something
}

In this case you can just say you want to display the error in order to correct it :

$res = mysqli->query($q) or exit mysqli_error();
artragis
  • 3,677
  • 1
  • 18
  • 30