How to Returns the error code from the last connection error (MySQLi) in PHP ?


In PHP, we can return the error code from the last connection error using the mysqli_connect_errno() function. This function returns the error code of the last connection error.

Here's an example:

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

// Check if the connection was successful
if (mysqli_connect_errno()) {
  // Connection failed, return the error code
  echo "Failed to connect to MySQL: " . mysqli_connect_errno();
  exit();
}

In the above example, we first create a connection using the mysqli_connect() function. We then check if the connection was successful using the mysqli_connect_errno() function. If the connection failed, we return the error code using the mysqli_connect_errno() function.

Another way to return the error code from the last connection error is by using the mysqli_errno() function. This function returns the error code of the last MySQLi function call.

Here's an example:

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

// Check if the connection was successful
if (!$conn) {
  // Connection failed, return the error code
  echo "Failed to connect to MySQL: " . mysqli_errno($conn);
  exit();
}

In the above example, we first create a connection using the mysqli_connect() function. We then check if the connection was successful using the !$conn condition. If the connection failed, we return the error code using the mysqli_errno() function.



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++.