Get the SQLSTATE error code for the last MySQL operation in PHP

Description

The following code shows how to get the SQLSTATE error code for the last MySQL operation.

Example


//  w w  w.  j av a 2  s .  co m
<?php
     $con=mysqli_connect("localhost","root","","test");
     // 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);
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    MySQL »




MySQLi
MySQLi Object Oriented