Php mysqli get errors

PHP mysqli: error() Function

The mysqli_error() function / mysqli::$error returns the last error description for the most recent function call, if any.

Object oriented style

Procedural style

string mysqli_error ( mysqli $link )
Name Description Required/Optional
link A link identifier returned by mysqli_connect() or mysqli_init() Required for procedural style only and Optional for Object oriented style

Usage: Procedural style

Return value:

A string that describes the error. An empty string if no error occurred.

Version: PHP 5, PHP 7

Example of object oriented style:

connect_errno) < printf("Connect failed: %s\n", $mysqli->connect_error); exit(); > if (!$mysqli->query("SET a=1")) < printf("Errormessage: %s\n", $mysqli->error); > /* close connection */ $mysqli->close(); ?> 
Errormessage: Unknown system variable 'a'

Example of procedural style:

 if (!mysqli_query($link, "SET a=1")) < printf("Errormessage: %s\n", mysqli_error($link)); >/* close connection */ mysqli_close($link); ?> 
Errormessage: Unknown system variable 'a'
 // Perform a query, check for error if (!mysqli_query($con,"INSERT INTO employees (First_Name) VALUES ('David')")) < echo("Errorcode: " . mysqli_errno($con)); >mysqli_close($con); ?> 

Previous: error_list
Next: field_count

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

Best way to find this is: create a php file and add the following code:

and open it in browser, it will show the file which is actually being read!

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How to report errors in mysqli

Add the following line before mysqli_connect() (or new mysqli() ):

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

Introduction

Reporting errors is the most essential thing in programming. A programmer is effectively deaf-blind if they cannot see errors occurred during the script execution. So it is very important to configure error reporting for your code properly, including database interactions.

By default, when you are running mysqli_query() or — preferably — prepare()/bind()/execute() , mysqli will just silently return false if a query fails, telling you nothing of the reason.

You’ll notice the error only when the following command, when trying to use the query result, will raise an error, such as

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.

Unfortunately, this error message tells you nothing of the actual problem. It just bluntly says that your query failed, and nothing else.

It happens because by default mysqli is configured to remain silent if a query returned an error. So you can tell that’s an extremely inconvenient behavior.

Luckily, mysqli can be configured to throw a PHP exception in case of a mysql error. It means that a PHP error will be thrown automatically every time a query returns an error, without any effort on your part!

Let’s see a small demonstration:

 // first of all set PHP error reporting in general
// in order to be sure we will see every error occurred in the script
ini_set('display_errors',1);
error_reporting(E_ALL);

/*** THIS! ***/
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
/*** ^^^^^ ***/
$db = $mysqli = new mysqli($host, $user, $pass, $database);

$res = $db->query("apparently not a valid SQL statement");
$res->fetch_assoc();

And run your script again. Whoa! An error appears in a puff of smoke, explaining what was the problem:

Fatal error: Uncaught exception 'mysqli_sql_exception'
with message 'You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'
apparently not valid SQL string' at line 1' in /home/www/test.php:16
Stack trace
:
#0 /home/www/init.php(16): mysqli->query('apparently not . ')
#1 /home/www/test.php(2): include('/home/www/. ')
#2
thrown in /home/www/init.php on line 16

As you can see, this is quite a detailed information, including the erroneous part of the query, and even a stack trace that helps you to find a particular function that called the erroneous query.

So again: just make sure that you always have this magic line before mysqli_connect() in all your scripts:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

What to do with the error message you get?

It should be a knee-jerk reflex to copy and paste the error message in Google search. It will lead you to several Stack Overflow questions related to this particular problem with many answers with solutions.

However, there is another possibility. You can try to actually read the error message you get. Usually, the error message explains it pretty straightforward, what is the error. However, some errors could be cryptic. You have to understand some considerations used in Mysql error messages:

  • in case of a syntax error, the cited query part begins right after the error.
  • it means that, therefore, if the error is at the very end of the query, the cited query part would be an empty string. Most likely it happens when you add a variable directly to the query and this variable happen to be empty (yet another reason to use prepared statements as they will make such errors just impossible to appear.
  • Mysqli tutorial (how to use it properly)
  • How to connect properly using mysqli
  • How to check whether a value exists in a database using mysqli prepared statements
  • Mysqli helper function
  • Why mysqli prepared statemens are so hard to use?
  • Authenticating a user using mysqli and password_verify()
  • How to get the number rows that has been actually changed
  • Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
  • Mysqli examples
  • Mysqli’s features you probably would like to know about
  • How to run INSERT query using Mysqli
  • How to use mysqli properly

Got a question?

I am the only person to hold a gold badge in , and on Stack Overflow and I am eager to show the right way for PHP developers.

Besides, your questions let me make my articles even better, so you are more than welcome to ask any question you have.

SEE ALSO:

  • Top 10 PHP delusions
  • PDO Examples
  • Mysqli Examples
  • Principles of web-programming
  • Mysqli tutorial (how to use it properly)
  • How to connect properly using mysqli
  • How to check whether a value exists in a database using mysqli prepared statements
  • Mysqli helper function
  • Why mysqli prepared statemens are so hard to use?
  • Authenticating a user using mysqli and password_verify()
  • How to get the number rows that has been actually changed
  • Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
  • Mysqli examples
  • Mysqli’s features you probably would like to know about
  • How to run INSERT query using Mysqli
  • How to use mysqli properly

Latest comments:

  • 28.07.23 14:08
    PHP programmer for (The only proper) PDO tutorial:
    In the section about transactions, you say that you should write . catch.
    read more
  • 24.07.23 01:16
    Tim Dawson for PDO Examples:
    Further to my previous reply to your e-mail, I now find that the following, with double quotes.
    read more
  • 23.07.23 16:47
    Tim Dawson for PDO Examples:
    I have a web site where visitors can look at accommodation reviews. A selection of reviews is.
    read more
  • 17.07.23 21:18
    Jim for (The only proper) PDO tutorial:
    Thanks for the reply! I was hoping you would know if what I’m attempting is even possible! :).
    read more
  • 16.07.23 00:35
    Jim for (The only proper) PDO tutorial:
    Hi, I just discovered this site today, so first and foremost, thank you for all your work.
    read more

Add a comment

Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator’s review.

Comments:

Reply:

Hello Daniel! That’s an interesting question. The simplest solution would be to upgrade the PHP version. Starting from 8.0 bind_param is throwing exceptions all right. For the older versions, it depends on what you need the exception for. Normally, there should be no difference: a Warning as in error all the same, it will be reported and the next call to execute will halt the code execution. But if you really need and exception, you can add a simple error handler to your code that would convert all errors to excepions, like

set_error_handler(function ($level, $message, $file = '', $line = 0)
throw new
ErrorException($message, 0, $level, $file, $line);
>);

See more at https://phpdelusions.net/articles/error_reporting Hope some of these suggestions will help. If not, then please let me know.

a bit misleading if all you have to do is call mysqli_error() and mysqli_errno() no need to reconfigure anything.

Reply:

Hello Chris! There are two problems with this mindset. First, the logic is somewhat inverted here: as long as you have to run only one SQL query, there is not much difference. But even with a dozen, not to mention hundreds of SQL queries, this «call mysqli_error() and mysqli_errno()» after every query becomes «a bit misleading». Now compare it with just «reconfiguring» a single line of code. Second, the question is, what you’re going to do with all these mysqli_error() and mysqli_errno() calls. Are you sure you are going to use them properly? And what if some day you will decide to change that behavior? For example, now you want to die() with the error message but eventually you will learn that it’s just gross and it needs to be changed. So, which approach will make it simpler: when you have just a single place where error reporting is configured, or when you have dozens to hundreds places where you need to rewrite the code?

Источник

PHP mysqli_error() Function

The mysqli_error() function returns the description of the error occurred during the last MySQLi function call.

Syntax

Parameters

This is an object representing a connection to MySQL Server.

Return Values

PHP mysqli_error() function returns an string value representing the description of the error from the last MySQLi function call. If there are no errors this function returns an empty string.

PHP Version

This function was first introduced in PHP Version 5 and works works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_error() function (in procedural style) −

This will produce following result −

Error Occurred: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FORM employee' at line 1

Example

In object oriented style the syntax of this function is $con ->error. Following is the example of this function in object oriented style −

 query("SELECT * FROM wrong_table_name"); //Error $error = $con ->error; print("Error Occurred: ".$error); //Closing the connection $con -> close(); ?>

This will produce following result −

Error Occurred: Table 'mydb.wrong_table_name' doesn't exist

Example

Following is another example of the mysqli_error() function −

This will produce following result −

Errors in the SELECT query: Errors in the UPDATE query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)' at line 1 Errors in the INSERT query: Unknown column 'Archana' in 'field list'

Example

 if (!mysqli_query($connection_mysql,"INSERT INTO employee (FirstName) VALUES ('Jack')")) < echo("Error description: " . mysqli_error($connection_mysql)); >mysqli_close($connection_mysql); ?>

This will produce following result −

Error description: Unknown column 'FirstName' in 'field list'

Источник

Читайте также:  Insert at position in list python
Оцените статью