PHP: mysqli_error - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysqli_escape_string mysqli_errno

Last updated: Sat, 27 Jan 2007

view this page in

# mysqli_error

(PHP 5)

mysqli_error -- Возвращает строку с описанием последней ошибки

## Описание

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

string mysqli_error ( mysqli link )

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

class mysqli {
string error
}

Функция mysqli_error() идентична функции mysqli_errno(), за исключением того, что вместо числового кода ошибки функция mysqli_error() вернет строковое описание последней ошибки, возникшей для соединение с базой данных, представленного параметром `link`. Если ошибок не возникнет, эта функция вернет пустую строку.

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

Строку, описывающую ошибку. Пустую строку, если ошибок не произошло.

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

mysqli_connect_errno(), mysqli_connect_error(), mysqli_errno() и mysqli_sqlstate().

## Примеры

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

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Проверка подключения */
if (mysqli_connect_errno()) {
printf("Ошибка подключения: %s\n", mysqli_connect_error());
exit();
}
if (!$mysqli->query("SET a=1")) {
printf("Ошибка: %s\n", $mysqli->error);
}
/* Закрытие соединения */
$mysqli->close();
?>`

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

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Проверка подключения */
if (mysqli_connect_errno()) {
printf("Ошибка подключения: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
printf("Ошибка: %s\n", mysqli_error($link));
}
/* Закрытие соединения */
mysqli_close($link);
?>`

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

    Ошибка: Unknown system variable 'a'

add a note User Contributed Notes
mysqli_error
se (at) brainbits (dot) net
20-Apr-2006 05:22
`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;")
}`
information at saunderswebsolutions dot com
24-Jan-2006 02:37
`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.`
information at saunderswebsolutions dot com
13-Jan-2006 02:52
`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:\classfiles\lib5\database.php(214): mysqli->query('select sess_val...')
#1 G:\classfiles\lib5\Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:\classfiles\includes.php(50): session_start()
#4 G:\tests\all_tests.php(4): include('G:\data\WorkSit...')
#5 {main}`
paul ate santasoft doit com
29-Jul-2005 06:50
`When migrating to PHP 5 from PHP 4, an important sticky note on the brain:
PHP 4 would default to the current connection (last opened connection) with mysql_error(). PHP 5 & mysqli, on the other hand, requires the link to be specified as in mysqli_error($link).
So if you are migrating and get a blank screen and don't know why, check your mysqli_* statements to ensure they include the $link if needed.
examples:
PHP 4:
<?php
$link = mysql_connect('localhost',''uid','pw');
$sql = 'some bad query';
$result = mysql_query($sql);
if (!mysql_num_rows($result)) {
echo(mysql_error());
} else {
echo('It Worked!!!!!!');
}
?>
PHP 5:
<?php
$link = mysqli_connect('localhost',''uid','pw');
$sql = 'some bad query';
$result = mysqli_query($link,$sql); // remember to include the link on queries too
if (!mysqli_num_rows($result)) {
echo(mysqli_error($link)); // aha!
} else {
echo('It Worked!!!!!!');
}
?>`
add a note
mysqli_escape_string mysqli_errno

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 10:36:09 2007 PST