How to Returns the SQLSTATE error code for the error (MySQLi) in PHP ?


In MySQLi, we can use the mysqli_sqlstate() function to return the SQLSTATE error code for the error. The SQLSTATE error code is a five-character alphanumeric identifier defined in the ANSI SQL standard.

Here's an example of how to use mysqli_sqlstate() function:

// Create a connection
$conn = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection is successful
if (!$conn) {
  // Get the SQLSTATE error code
  $sqlstate = mysqli_sqlstate($conn);
  echo "Connection failed. SQLSTATE error code: " . $sqlstate;
  exit;
}

In the above example, we first create a connection to the database using the mysqli_connect() function. We then check if the connection is successful using the !$conn condition. If the connection fails, we use the mysqli_sqlstate() function to get the SQLSTATE error code and display it to the user.

Another way to get the SQLSTATE error code is by using the mysqli_errno() function. This function returns the error code for the most recent MySQLi function call. Here's an example:

// Create a connection
$conn = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection is successful
if (!$conn) {
  // Get the error code
  $error_code = mysqli_errno($conn);
  echo "Connection failed. Error code: " . $error_code;
  exit;
}

In the above example, we use the mysqli_errno() function to get the error code for the most recent MySQLi function call. If the connection fails, we display the error code to the user.

Both of these methods can be used to get the SQLSTATE error code for the error in MySQLi.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.