2

I am new to PHP and prepared SQL sentences and I got one question when reading the documentation.

Function 'mysqli.prepare' returns a boolean value when executed. According to the documentation:

mysqli_prepare() returns a statement object or FALSE if an error occurred.

That's not a very detailed description of the returned value. I mean, when does it exactly fail? Only when the SQL syntax is not correct? Or when we try to execute it and it does not work for any other reason (I base this last supposition on the example shown on the documentation, where almost all the script is enclosed in an if statement)

Based on this, I also have a second question: is it a good practice to run mysqli_prepare() together with an if? Or should the if statement be written when we run the $stmt->execute(); function later on?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rors
  • 159
  • 2
  • 10

1 Answers1

-1

There are too many reasons why a query can fail. But when the query failed you can get the error message with mysqli_error() and mysqli_errno(). When the query failed the mysqli_prepare() function will return FALSE (and not a MySQLi prepared statement object) to indicate that there was an error. You have to check the return value with an if() statement to handle this case. If you don't check it and try to run $stmt->execute(); you will get an error that you cannot run the execute() method on a boolean value (the value false).

For your second question: You have to check the return value of mysqli_prepare() and you have to check the return value of mysqli_stmt_execute(). You cannot skip the check, otherwise you get errors like mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • 1
    You can skip the check and you do not need to check with `if` statement. Actually this is a terrible practice and should be avoided! [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Oct 31 '19 at 22:03