PHP mysqli_sqlstate() 函数



定义和用法

mysqli_sqlstate() 函数返回在上次 MySQLi 函数调用(MySQL 操作)期间发生的 SQLSTATE 错误。

语法

mysqli_sqlstate($con)

参数

序号 参数及描述
1

con(必填)

这是一个表示与 MySQL 服务器连接的对象。

返回值

PHP mysqli_sqlstate() 函数返回一个字符串值,表示在上次 MySQL 操作期间发生的 SQLSTATE 错误。如果没有错误,此函数返回 00000

PHP 版本

此函数首次引入于 PHP 5 版本,并在所有后续版本中均有效。

示例

以下示例演示了 mysqli_sqlstate() 函数的用法(过程式风格)−

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to retrieve all the records of a table
   mysqli_query($con, "Select * from WrongTable");

   //SQL State
   $state = mysqli_sqlstate($con);
   print("SQL State Error: ".$state);

   //Closing the connection
   mysqli_close($con);
?>

这将产生以下结果−

SQL State Error: 42S02

示例

在面向对象风格中,此函数的语法为 $con ->sqlstate。以下是此函数在面向对象风格中的示例−

<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   //Query to retrieve all the records of the employee table
   $con -> query("Select FIRST_NAME, LAST_NAME, AGE form employee");

   //SQL State
   $state = $con->sqlstate;
   print("SQL State Error: ".$state);

   //Closing the connection
   $con -> close();
?>

这将产生以下结果−

SQL State Error: 42000

示例

以下是 mysqli_sqlstate() 函数的另一个示例−

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to SELECT all the rows of the employee table
   mysqli_query($con, "SELECT * FROM employee");
   print("SQL State Error: ".mysqli_sqlstate($con)."\n");

   //Query to UPDATE the rows of the employee table
   mysqli_query($con, "UPDATE employee set INCOME=INCOME+5000 where FIRST_NAME in (*)");
   print("SQL State Error: ".mysqli_sqlstate($con)."\n");

   //Query to INSERT a row into the employee table
   mysqli_query($con, "INSERT INTO employee VALUES (Archana, 'Mohonthy', 30, 'M', 13000, 106)");
   print("SQL State Error: ".mysqli_sqlstate($con)."\n");

   //Closing the connection
   mysqli_close($con);
?>

这将产生以下结果−

SQL State Error: 00000
SQL State Error: 42000
SQL State Error: 42S22

示例

<?php
   $connection_mysql = mysqli_connect("localhost", "root", "password", "mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   //Assume we already have a table named Persons in the database mydb
   $sql = "CREATE TABLE Persons (Firstname VARCHAR(30),Lastname VARCHAR(30),Age INT)";
   
   if (!mysqli_query($connection_mysql,$sql)){
      echo "SQLSTATE error: ". mysqli_sqlstate($connection_mysql);
   }
   
   mysqli_close($connection_mysql);
?>

这将产生以下结果−

SQLSTATE error: 42S01
php_function_reference.htm
广告