PHP Function Reference

PHP mysqli $sqlstate Property



The PHP mysqli::$sqlstate / mysqli_sqlstate() function returns the SQLSTATE error code for the most recent MySQLi function 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.

Note: Not all MySQL errors are mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Syntax

//Object-oriented style
$mysqli->sqlstate;

//Procedural style
mysqli_sqlstate(mysql)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_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::$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();
}

//executing an SQL query
$sql = "SET x=1";

if (!$mysqli->query($sql)) {
  printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

Error - SQLSTATE HY000.

Example: Procedural style

The example below shows the usage of mysqli_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();
}

//executing an SQL query
$sql = "SET x=1";

if (!mysqli_query($mysqli, $sql)) {
  printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($mysqli));
}

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

Error - SQLSTATE HY000.

❮ PHP MySQLi Reference