PHP mysqli $error Property
The PHP mysqli::$error / mysqli_error() function returns the last error message for the most recent MySQLi function call that can succeed or fail.
Syntax
//Object-oriented style $mysqli->error; //Procedural style mysqli_error(mysql)
Parameters
mysql |
Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init(). |
Return Value
Returns a string that describes the error. An empty string if no error occurred.
Example: Object-oriented style
The example below shows the usage of mysqli::$error property.
<?php //establishing connection to the database $mysqli = new mysqli("localhost", "user", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: ". $mysqli->connect_error; exit(); } //executing an SQL query $sql = "SET x=1"; if (!$mysqli->query($sql)) { printf("Error message: %s\n", $mysqli->error); } //closing the connection $mysqli->close(); ?>
The output of the above code will be similar to:
Error message: Unknown system variable 'x'
Example: Procedural style
The example below shows the usage of mysqli_error() function.
<?php //establishing connection to the database $mysqli = mysqli_connect("localhost", "user", "password", "database"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: ". mysqli_connect_error(); exit(); } //executing an SQL query $sql = "SET x=1"; if (!mysqli_query($mysqli, $sql)) { printf("Error message: %s\n", mysqli_error($mysqli)); } //closing the connection mysqli_close($mysqli); ?>
The output of the above code will be similar to:
Error message: Unknown system variable 'x'
❮ PHP MySQLi Reference