Mysql get last error

(PHP 5, PHP 7, PHP 8)

mysqli_error

(PHP 5, PHP 7, PHP 8)

mysqli::$errormysqli_errorВозвращает строку с описанием последней ошибки

Описание

Объектно-ориентированный стиль

Процедурный стиль

mysqli_error(mysqli $mysql): string

Возвращаемые значения

Строка с описанием ошибки. Пустая строка, если ошибки нет.

Примеры

Пример #1 Пример с $mysqli->error

Объектно-ориентированный стиль


<?php
$mysqli
= new mysqli("localhost", "my_user", "my_password", "world");/* Проверить соединение */
if ($mysqli->connect_errno) {
printf("Соединение не удалось: %sn", $mysqli->connect_error);
exit();
}

if (!

$mysqli->query("SET a=1")) {
printf("Сообщение ошибки: %sn", $mysqli->error);
}
/* Закрыть соединение */
$mysqli->close();
?>

Процедурный стиль


<?php
$link
= mysqli_connect("localhost", "my_user", "my_password", "world");/* Проверить соединение */
if (mysqli_connect_errno()) {
printf("Соединение не удалось: %sn", mysqli_connect_error());
exit();
}

if (!

mysqli_query($link, "SET a=1")) {
printf("Сообщение ошибки: %sn", mysqli_error($link));
}
/* Закрыть соединение */
mysqli_close($link);
?>

Результат выполнения данных примеров:

Сообщение ошибки: Unknown system variable 'a'

Смотрите также

  • mysqli_connect_errno() — Возвращает код ошибки последней попытки соединения
  • mysqli_connect_error() — Возвращает описание последней ошибки подключения
  • mysqli_errno() — Возвращает код ошибки последнего вызова функции
  • mysqli_sqlstate() — Возвращает код состояния SQLSTATE последней MySQL операции

information at saunderswebsolutions dot com

17 years ago


The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
<?php
$query
= "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!

$res) {
  
printf("Errormessage: %sn", $mysqli->error);
}
?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
<?php
$query
= "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!

$mysqli->error) {
  
printf("Errormessage: %sn", $mysqli->error);
}
?>

This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

<?php
mysqli_report
(MYSQLI_REPORT_OFF); //Turn off irritating default messages$mysqli = new mysqli("localhost", "my_user", "my_password", "world");$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (

$mysqli->error) {
    try {   
        throw new
Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);   
    } catch(
Exception $e ) {
        echo
"Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
        echo
nl2br($e->getTraceAsString());
    }
}
//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table

#0 G:\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:dataWorkSites1framework5testsdbtest.php(29): database->getString('SELECT XXname F...')
#2 c:PHPincludessimpletestrunner.php(58): testOfDB->testGetVal()
#3 c:PHPincludessimpletestrunner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:PHPincludessimpletestrunner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:PHPincludessimpletestrunner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:PHPincludessimpletestsimple_test.php(90): SimpleRunner->run()
#7 c:PHPincludessimpletestsimple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:PHPincludessimpletestsimple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.


se (at) brainbits (dot) net

16 years ago


The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

if (!$mysqli->query("SET a=1")) {
   $mysqli->query("ROLLBACK;")
   printf("Errormessage: %sn", $mysqli->error);
}

you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:

if (!$mysqli->query("SET a=1")) {
   printf("Errormessage: %sn", $mysqli->error);
   $mysqli->query("ROLLBACK;")
}


callforeach at gmail dot com

7 years ago


I had to set mysqli_report(MYSQLI_REPORT_ALL) at the begin of my script to be able to catch mysqli errors within the catch block of my php code.

Initially, I used the below code to throw and subsequent catch mysqli exceptions

<?php
try {
  
$mysqli = new mysqli('localhost','root','pwd','db');
    if (
$mysqli->connect_errno)
        throw new
Exception($mysqli->connect_error);

} catch (

Exception $e) {
     echo
$e->getMessage();
}
I realized the exception was being thrown before the actual throw statement and hence the catch block was not being called.My current code looks like
mysqli_report
(MYSQLI_REPORT_ALL) ;
try {
     
$mysqli = new mysqli('localhost','root','pwd','db');
     
/* I don't need to throw the exception, it's being thrown automatically */} catch (Exception $e) {
  echo
$e->getMessage();
}
This works fine and I'm able to trap all mysqli errors


abderrahmanekaddour dot aissat at gmail dot com

5 months ago


<?php// The idea is the add formated errors information for developers to easier bugs detection.$myfile = fopen("database_log.log", "r");
$db = new mysqli("localhost", "root","root","data");
if(!
$db->query("SELECT")){
 
$timestamp = new DateTime();
 
$data_err = " {
     "title": " Select statement error ",
     "date_time": "
.$timestamp->getTimestamp().",
     "error":" "
.$db->error." "
     } "
; // Do more information
 
fwrite($myfile, $data_err); // writing data
}
   
// In separate file do file read and format it for good visual.$db->close(); 
fclose($myfile);
?>

asmith16 at littlesvr dot ca

9 years ago


Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.

So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().

As far as I can tell the two escape functions don't escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).


information at saunderswebsolutions dot com

17 years ago


Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
<?php
//set up $mysqli_instance here..
$Select = "SELECT xyz FROM mytable ";
try {
   
$res = $mysqli_instance->query($Select);
}catch (
mysqli_sql_exception $e) {
    print
"Error Code <br>".$e->getCode();
    print
"Error Message <br>".$e->getMessage();
    print
"Strack Trace <br>".nl2br($e->getTraceAsString());
}
?>
Will print out something like
Error Code: 0
Error Message
No index used in query/prepared statement select sess_value from frame_sessions where sess_name = '5b85upjqkitjsostvs6g9rkul1'
Strack Trace:
#0 G:classfileslib5database.php(214): mysqli->query('select sess_val...')
#1 G:classfileslib5Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:classfilesincludes.php(50): session_start()
#4 G:testsall_tests.php(4): include('G:dataWorkSit...')
#5 {main}

Anonymous

3 years ago


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
                $this->connection = mysqli_connect($hostname,$username,$password, $dbname);
} catch (Exception $e) {
                echo "Errno: " . mysqli_connect_errno() . PHP_EOL;
                echo "Text error: " . mysqli_connect_error() . PHP_EOL;
                exit;
}

Last update on August 19 2022 21:51:16 (UTC/GMT +8 hours)

mysqli_error() function / mysqli::$error

The mysqli_error() function / mysqli::$error returns the last error description for the most recent function call, if any.

Syntax:

Object oriented style

string $mysqli->error;

Procedural style

string mysqli_error ( mysqli $link )

Parameter:

Name Description Required/Optional
link A link identifier returned by mysqli_connect() or mysqli_init() Required for procedural style only and Optional for Object oriented style

Usage: Procedural style

mysqli_error(connection);

Parameter:

Name Description Required/Optional
connection Specifies the MySQL connection to use. Required

Return value:

A string that describes the error. An empty string if no error occurred.

Version: PHP 5, PHP 7

Example of object oriented style:

<?php
$mysqli = new mysqli("localhost", "user1", "datasoft123", "hr");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %sn", $mysqli->connect_error);
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errormessage: %sn", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Output:

Errormessage: Unknown system variable 'a'

Example of procedural style:

<?php

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %sn", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errormessage: %sn", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

Output:

Errormessage: Unknown system variable 'a'

Example:

<?php
$con=mysqli_connect("localhost","user1","datasoft123","hr");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO employees (First_Name) VALUES ('David')"))
  {
  echo("Errorcode: " . mysqli_errno($con));
  }

mysqli_close($con);
?>

Sample Output:

Errorcode: 1146

See also

PHP Function Reference

Previous: error_list

Next: field_count

PHP: Tips of the Day

PHP — Generating a random password in PHP

Security warning: rand() is not a cryptographically secure pseudorandom number generator. Look elsewhere for generating a cryptographically secure pseudorandom string in PHP.

Try this (use strlen instead of count, because count on a string is always 1):

function randomPassword() {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

Ref : https://bit.ly/39BNAs0

За последние 24 часа нас посетили 11453 программиста и 1126 роботов. Сейчас ищут 292 программиста …

mysqli::$error

mysqli_error

(PHP 5, PHP 7)

mysqli::$errormysqli_errorВозвращает строку с описанием последней ошибки

Описание

Объектно-ориентированный стиль

Процедурный стиль

string mysqli_error
( mysqli $link
)

Возвращаемые значения

Строка с описанием ошибки. Пустая строка, если ошибки нет.

Примеры

Пример #1 Пример с $mysqli->error

Объектно-ориентированный стиль


<?php
$mysqli 
= new mysqli("localhost""my_user""my_password""world");/* check connection */
if ($mysqli->connect_errno) {
    
printf("Connect failed: %sn"$mysqli->connect_error);
    exit();
}

if (!

$mysqli->query("SET a=1")) {
    
printf("Errormessage: %sn"$mysqli->error);
}
/* close connection */
$mysqli->close();
?>

Процедурный стиль


<?php
$link 
mysqli_connect("localhost""my_user""my_password""world");/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %sn"mysqli_connect_error());
    exit();
}

if (!

mysqli_query($link"SET a=1")) {
    
printf("Errormessage: %sn"mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>

Результат выполнения данных примеров:

Errormessage: Unknown system variable 'a'

Смотрите также

  • mysqli_connect_errno() — Возвращает код ошибки последней попытки соединения
  • mysqli_connect_error() — Возвращает описание последней ошибки подключения
  • mysqli_errno() — Возвращает код ошибки последнего вызова функции
  • mysqli_sqlstate() — Возвращает код состояния SQLSTATE последней MySQL операции

Вернуться к: mysqli

  1. PHP MySQLi Error Functions
  2. Conclusion

Display Errors Using MySQLi Error Functions

MySQLi is a PHP function used to access the MySQL database server. You can use this extension if you have MySQL version 4.1.13 or above.

There are various MySQLi functions that you can use to perform different functions in PHP. In this article, we will learn MySQLi error functions.

We will also see how and where to use code examples and observe the outputs. For this tutorial, we will use MySQL version 8.0.27 and PHP version 7.4.1.

PHP MySQLi Error Functions

In this tutorial, we will learn about the following PHP MySQLi error functions:

  • mysqli_error()
  • mysqli_errno()
  • mysqli_error_list()
  • mysqli_connect_error()
  • mysqli_connect_errno()

All these functions can be used in object-oriented style and procedural style. Let’s understand both syntax using the mysqli_error() function.

Syntax of mysqli_error() Function in Object Oriented Style

Syntax of mysqli_error() Function in Procedural Style

string mysqli_error ( mysqli $link )

mysqli_error() Function in MySQL

This function is used to output the last error description for the most recent function call (if there is any). It is used when you want to know whether the SQL query has an error or not.

mysqli_error() returns the error description and empty string if there is no error. See the following example.

Example Code Using Procedural Style:

<?php
    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "person";

    $connection = mysqli_connect($host, $username, $password, $database) 
    or die("Connection Failed"); 

    $sql = "SELECT * FROM teacher";
    $result = mysqli_query($connection, $sql);
    $error_message = mysqli_error($connection);

    if($error_message == ""){
        echo "No error related to SQL query.";
    }else{
        echo "Query Failed: ".$error_message;
    }
    mysqli_close($connection);
?>

The code given above tries to make the connection using $host, $username, $password, $database variables and save this connection into the $connection variable.

mysqli_error() function will take this connection variable $connection as a parameter and check if there is any error caused by the recent MySQLi function call which is mysqli_query($connection, $sql) here.

Output:

display errors using mysqli error functions - no error using mysqli_error

Now, change the table name in the SQL query from teacher to person and observe the output given below.

Output:

display errors using mysqli error functions - error using mysqli_error

We, as a developer, can easily understand that there is no person table in the person database (this is what it means in the above error).

Keep the table name changed and replace the line $error_message = mysqli_error($connection); with $error_message = $connection->error; to practice and understand the object oriented style using MySQLi error function.

mysqli_errno() Function in MySQL

mysqli_errno() works the same as mysqli_error() does, but it will return the error code instead of the error description.

Write the following code to practice and understand. You may have noticed that we use a procedural style to practice this function.

<?php
     $host = "localhost";
     $username = "root";
     $password = "";
     $database = "person";

     $connection = mysqli_connect($host, $username, $password, $database) 
     or die("Connection Failed"); 

     $sql = "SELECT * FROM person";
     $result = mysqli_query($connection, $sql);
     $error_message = mysqli_errno($connection);

     if($error_message == ""){
     	echo "No error related to SQL query.";
     }else{
     	echo "Query Failed: ".$error_message;
     }
    mysqli_close($connection);
?>

The code given above will show the following output where you will see a number as an error code.

Output:

display errors using msyqli error functions - error using mysqli_errno

The question is, why do we use this function to show the numbers only? Because if you want to print a user-friendly error message (custom message), you can use this error code in if-else statements.

See the following code and its output below.

<?php
     $host = "localhost";
     $username = "root";
     $password = "";
     $database = "person";

     $connection = mysqli_connect($host, $username, $password, $database) 
     or die("Connection Failed"); 

     $sql = "SELECT * FROM person";
     $result = mysqli_query($connection, $sql);
     $error_message = mysqli_errno($connection);

     if($error_message == 1146){
     	echo "You are trying to read the data from a table which doesn't exist in your 			database "."'".$database."'";
     }
    mysqli_close($connection);
?>

Output:

display errors using mysqli error functions - custom error message using mysqli_errno.png

mysqli_error_list() Function in MySQL

This function is very useful for knowing the error code, SQL state, and error description because this function returns an array containing all the necessary information.

Example Code:

<?php
     $host = "localhost";
     $username = "root";
     $password = "";
     $database = "person";

     $connection = mysqli_connect($host, $username, $password, $database) 
     or die("Connection Failed"); 

     $sql = "SELECT * FROM person";
     $result = mysqli_query($connection, $sql);
     print_r(mysqli_error_list($connection));
     mysqli_close($connection);
?>

Output:

display errors using mysqli error functions - error list using mysqli_error_list

mysqli_connect_error() Function in MySQL

mysqli_connect_error() returns the error description from the last connection if there is any. Although, the die() function also tell about the unsuccessful connection but mysqli_connect_error() returns the error that we can understand easily.

Write the following code first, see its output, and then we’ll compare it with the output produced by mysqli_connect_error().

<?php
     $host = "localhost";
     $username = "root";
     $password = "";
     $database = "person";

     $connection = mysqli_connect($host, $username, $password, $database) 
     or die("Connection Failed"); 

     $sql = "SELECT * FROM person";
     $result = mysqli_query($connection, $sql);
     $error_message = mysqli_error($connection);

     if($error_message != ""){
     	echo "Query Failed: ".$error_message;
      }
    mysqli_close($connection);
?>

Output:

display errors using mysqli error functions - error using mysqli_connect_error part a

See the output given above; you can see that the error we can understand is somewhere in the middle.

Imagine, if you have 2 or 3 errors, it would not be easy to find out. Now, use the mysqli_connect_error() and see the difference using the following code and output.

<?php
     $host = "localhost";
     $username = "newroot";
     $password = "";
     $database = "person";

     $connection = mysqli_connect($host, $username, $password, $database) 
     or die("Connection Failed: ".mysqli_connect_error()); 

     $sql = "SELECT * FROM teacher";
     $result = mysqli_query($connection, $sql);
     $error_message = mysqli_error($connection);

     if($error_message != ""){
     	echo "SQL Query Failed: ".$error_message;
    }
    mysqli_close($connection);
?>

Output:

display errors using mysqli error functions - error using mysqli_connect_error part b

The above output clearly says that there is no user named newroot, which does not allow you to access the database.

mysqli_connect_errno() Function in MySQL

This function behaves like mysqli_connect_error() but displays the error code rather than the error message. We can use this error code to write custom error messages.

Example Code:

<?php
     $host = "localhost";
     $username = "newroot";
     $password = "";
     $database = "person";

     $connection = mysqli_connect($host, $username, $password, $database) 
     or die("Connection Failed: ".mysqli_connect_errno()); 

     $sql = "SELECT * FROM teacher";
     $result = mysqli_query($connection, $sql);
     $error_message = mysqli_error($connection);

     if($error_message != ""){
	     echo "SQL Query Failed: ".$error_message;
     }
     mysqli_close($connection);
?>

Output:

display errors using mysqli error functions - error using mysqli_connect_errno

Conclusion

Considering all the discussion and examples, we have concluded two main categories. The first category shows the errors about SQL queries and the other about database connections.

Depending on the project needs, we can print the error message or the error code in each category.

Понравилась статья? Поделить с друзьями:
  • Mysql failed error your password does not satisfy the current policy requirements
  • Mysql error что это значит на сайте
  • Mysql error вывод
  • Mysql error you have an error in your sql syntax error
  • Mysql error while reading greeting packet