PHP mysqli: sqlstate() function
mysqli_sqlstate() function / mysqli::$sqlstate
The mysqli_sqlstate() function / mysqli::$sqlstate 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
string $mysqli->sqlstate;
Procedural style
string mysqli_sqlstate ( mysqli $link )
Parameter:
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
mysqli_sqlstate(connection);
Parameter:
Name | Description | Required/Optional |
---|---|---|
connection | Specifies the MySQL connection to use | Required |
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.
Version: PHP 5, PHP 7
Example of object oriented style:
<?php
$mysqli = new mysqli("localhost", "user1", "datasoft123", "hr");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Table City already exists, so we should get an error */
if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}
$mysqli->close();
?>
Output:
Error - SQLSTATE 42S01.
Example of the Procedural style
<?php
$link = mysqli_connect("localhost", "user1", "datasoft123", "hr");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Table City already exists, so we should get an error */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}
mysqli_close($link);
?>
Output:
Error - SQLSTATE 42S01.
Example:
<?php
$con=mysqli_connect("localhost","user1","datasoft123","hr");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// 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);
?>
See also
Previous: set_local_infile_handler
Next: ssl_set
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php/function-reference/mysqli_sqlstate.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics