PHP mysqli_stmt $sqlstate Property
The PHP mysqli_stmt::$sqlstate / mysqli_stmt_sqlstate() function returns the SQLSTATE error code for the most recent statement call that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.
Syntax
//Object-oriented style $mysqli_stmt->sqlstate; //Procedural style mysqli_stmt_sqlstate(statement)
Parameters
statement |
Required. For procedural style only: Specify a mysqli_stmt object returned by mysqli_stmt_init(). |
Return Value
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Example: Object-oriented style
The example below shows the usage of mysqli_stmt::$sqlstate property.
<?php //establishing connection to the database $mysqli = new mysqli("localhost", "user", "password", "database"); if ($mysqli->connect_sqlstate) { echo "Failed to connect to MySQL: ". $mysqli->connect_error; exit(); } $sql = "SELECT Name, Age FROM Employee ORDER BY Age"; if ($stmt = $mysqli->prepare($sql)) { //dropping the table $mysqli->query("DROP TABLE Employee"); //executing the query $stmt->execute(); printf("Error: %s \n", $stmt->sqlstate); //closing the statement $stmt->close(); } //closing the connection $mysqli->close(); ?>
The output of the above code will be similar to:
Error: 42S02
Example: Procedural style
The example below shows the usage of mysqli_stmt_sqlstate() function.
<?php //establishing connection to the database $mysqli = mysqli_connect("localhost", "user", "password", "database"); if (mysqli_connect_sqlstate()) { echo "Failed to connect to MySQL: ". mysqli_connect_error(); exit(); } $sql = "SELECT Name, Age FROM Employee ORDER BY Age"; if ($stmt = mysqli_prepare($mysqli, $sql)) { //dropping the table mysqli_query($mysqli, "DROP TABLE Employee"); //executing the query mysqli_stmt_execute($stmt); printf("Error: %s \n", mysqli_stmt_sqlstate($stmt)); //closing the statement mysqli_stmt_close($stmt); } //closing the connection mysqli_close($mysqli); ?>
The output of the above code will be similar to:
Error: 42S02
❮ PHP MySQLi Reference