Current Location: Home> Function Categories> mysqli::$sqlstate

mysqli::$sqlstate

(mysqli_sqlstate) Returns SQLSTATE error for previous MySQL operation
Name:mysqli::$sqlstate
Category:MySQLi
Programming Language:php
One-line Description:Returns the wrong SQLSTATE error code.

Definition and usage

sqlstate / mysqli_sqlstate() function returns the last error SQLSTATE error code.

The error code consists of five characters. "00000" means there is no error. These values ​​are specified by ANSI SQL and ODBC.

Example

Example 1 - Object-Oriented Style

Returns the last error SQLSTATE error code:

 <?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 ( ) ;
?>

Example 2 - Procedural Style

Returns the last error SQLSTATE error code:

 <?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

// Check the 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 ) ;
?>
Similar Functions
Popular Articles