mysqli::$error

mysqli_error

(PHP 5, PHP 7, PHP 8)

mysqli::$error -- mysqli_errorDevuelve una cadena que describe el último error

Descripción

Estilo orientado a objetos

Estilo por procedimientos

mysqli_error(mysqli $link): string

Devuelve el últmo mensaje de error para la llamada más reciente a una función de MySQLi que puede haberse ejecutado correctamente o haber fallado.

Parámetros

link

Sólo estilo por procediminetos: Un identificador de enlace devuelto por mysqli_connect() o mysqli_init()

Valores devueltos

Una cadena que describe el error. Una cadena vacía si no ha ocurrido error alguno.

Ejemplos

Ejemplo #1 Ejemplo de $mysqli->error

Estilo orientado a objetos

<?php
$mysqli
= new mysqli("localhost", "my_user", "my_password", "world");

/* Comprueba la conexión */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

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

/* Cierra la conexión */
$mysqli->close();
?>

Estilo por procedimientos

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

/* Comprueba la conexión */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

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

/* Cierra la conexión */
mysqli_close($link);
?>

El resultado de los ejemplos sería:

Errormessage: Unknown system variable 'a'

Ver también

add a note

User Contributed Notes 5 notes

up
17
information at saunderswebsolutions dot com
18 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: %s\n", $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: %s\n", $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:\data\WorkSites\1framework5\tests\dbtest.php(29): database->getString('SELECT XXname F...')
#2 c:\PHP\includes\simpletest\runner.php(58): testOfDB->testGetVal()
#3 c:\PHP\includes\simpletest\runner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:\PHP\includes\simpletest\runner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:\PHP\includes\simpletest\runner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:\PHP\includes\simpletest\simple_test.php(90): SimpleRunner->run()
#7 c:\PHP\includes\simpletest\simple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:\PHP\includes\simpletest\simple_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.
up
9
se (at) brainbits (dot) net
18 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: %s\n", $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: %s\n", $mysqli->error);
$mysqli->query("ROLLBACK;")
}
up
6
callforeach at gmail dot com
9 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
up
-2
asmith16 at littlesvr dot ca
10 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).
up
-1
abderrahmanekaddour dot aissat at gmail dot com
2 years 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);
?>
To Top