当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


PHP mysqli_sqlstate()用法及代码示例


定义和用法

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

用法

mysqli_sqlstate($con)

参数

Sr.No 参数及说明
1

con(Mandatory)

这是一个表示与 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 mysqli_sqlstate() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。