PHP mysqli sqlstate() Function
Example - Object Oriented style
Return the SQLSTATE error code for the last error:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// Table Persons already exists, so we should get an error
$sql = "CREATE TABLE Persons (Firstname VARCHAR(30), Lastname VARCHAR(30), Age INT)"
if (!$mysqli
-> query($sql)) {
echo "SQLSTATE error: ". $mysqli -> sqlstate;
}
$mysqli -> close();
?>
Look at example of procedural style at the bottom.
Definition and Usage
The sqlstate / mysqli_sqlstate() function returns the SQLSTATE error code for the last error.
The error code consists of five characters. "00000" indicates no error. The values are specified by ANSI SQL and ODBC.
Syntax
Object oriented style:
$mysqli -> sqlstate
Procedural style:
mysqli_sqlstate(connection)
Parameter Values
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
Technical Details
Return Value: | A string containing the SQLSTATE error code for the last error |
---|---|
PHP Version: | 5+ |
Example - Procedural state
Return the SQLSTATE error code for the last error:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
// Table Persons already exists, so we should get an error
$sql = "CREATE TABLE Persons (Firstname VARCHAR(30), Lastname VARCHAR(30), Age INT)"
if (!mysqli_query($con, $sql)) {
echo "SQLSTATE error: ". mysqli_sqlstate($con);
}
// Close connection
mysqli_close($con);
?>
❮ PHP mysqli Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.