PHP mysqli_error() 函数



定义和用法

mysqli_error() 函数返回上次 MySQLi 函数调用期间发生的错误的描述。

语法

mysqli_error($con)

参数

序号 参数及描述
1

con(必填)

这是代表与 MySQL 服务器连接的对象。

返回值

PHP mysqli_error() 函数返回一个字符串值,该值表示上次 MySQLi 函数调用的错误描述。如果没有错误,则此函数返回空字符串。

PHP 版本

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

示例

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

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

   //Query to retrieve all the rows of employee table
   mysqli_query($con, "SELECT * FORM employee");

   //Error
   $error = mysqli_error($con);
   print("Error Occurred: ".$error);

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

这将产生以下结果 −

Error Occurred: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FORM employee' at line 1

示例

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

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

   //Query to retrieve all the rows of employee table
   $con -> query("SELECT * FROM wrong_table_name");

   //Error 
   $error = $con ->error;
   print("Error Occurred: ".$error);

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

这将产生以下结果 −

Error Occurred: Table 'mydb.wrong_table_name' doesn't exist

示例

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

<?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("Errors in the SELECT query: ".mysqli_error($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("Errors in the UPDATE query: ".mysqli_error($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("Errors in the INSERT query: ".mysqli_error($con)."\n");
  
   //Closing the connection
   mysqli_close($con);
?>

这将产生以下结果 −

Errors in the SELECT query:
Errors in the UPDATE query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)' at line 1
Errors in the INSERT query: Unknown column 'Archana' in 'field list'

示例

<?php
   $connection_mysql = mysqli_connect("localhost","root","password","mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   if (!mysqli_query($connection_mysql,"INSERT INTO employee (FirstName) VALUES ('Jack')")){
      echo("Error description: " . mysqli_error($connection_mysql));
   }
   
   mysqli_close($connection_mysql);
?>

这将产生以下结果 −

Error description: Unknown column 'FirstName' in 'field list'
php_function_reference.htm
广告