Mysqli error exception

(PHP 5, PHP 7, PHP 8)

mysqli_error

(PHP 5, PHP 7, PHP 8)

mysqli::$errormysqli_errorReturns a string description of the last error

Description

Object-oriented style

Procedural style

mysqli_error(mysqli $mysql): string

Return Values

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

Examples

Example #1 $mysqli->error example

Object-oriented style


<?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("Error message: %sn", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>

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("Error message: %sn", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>

The above examples will output:

Error message: Unknown system variable 'a'

See Also

  • mysqli_connect_errno() — Returns the error code from last connect call
  • mysqli_connect_error() — Returns a description of the last connection error
  • mysqli_errno() — Returns the error code for the most recent function call
  • mysqli_sqlstate() — Returns the SQLSTATE error from previous MySQL operation

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;
}

Содержание

  1. mysqli::$error
  2. Description
  3. Parameters
  4. Return Values
  5. Examples
  6. See Also
  7. User Contributed Notes 7 notes
  8. mysqli::$connect_error
  9. Описание
  10. Список параметров
  11. Возвращаемые значения
  12. Примеры
  13. Смотрите также
  14. mysqli::__construct
  15. mysqli_connect
  16. Описание
  17. Список параметров
  18. Возвращаемые значения
  19. Ошибки
  20. Примеры
  21. Примечания
  22. Смотрите также
  23. User Contributed Notes 13 notes

mysqli::$error

(PHP 5, PHP 7, PHP 8)

mysqli::$error — mysqli_error — Returns a string description of the last error

Description

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parameters

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

Return Values

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

Examples

Example #1 $mysqli->error example

= 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 ( «Error message: %sn» , $mysqli -> error );
>

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

= 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 ( «Error message: %sn» , mysqli_error ( $link ));
>

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

The above examples will output:

See Also

  • mysqli_connect_errno() — Returns the error code from last connect call
  • mysqli_connect_error() — Returns a description of the last connection error
  • mysqli_errno() — Returns the error code for the most recent function call
  • mysqli_sqlstate() — Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes 7 notes

The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
= «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:
= «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() [function.query]: (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:

( 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
Query:
$query » , $msqli -> errno );
> catch( Exception $e ) <
echo «Error No: » . $e -> getCode (). » — » . $e -> getMessage () . «
» ;
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.

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;»)
>

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

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

// 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 );
?>

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).

Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
//set up $mysqli_instance here..
$Select = «SELECT xyz FROM mytable » ;
try <
$res = $mysqli_instance -> query ( $Select );
>catch ( mysqli_sql_exception $e ) <
print «Error Code
» . $e -> getCode ();
print «Error Message
» . $e -> getMessage ();
print «Strack Trace
» . nl2br ( $e -> getTraceAsString ());
>

Источник

mysqli::$connect_error

(PHP 5, PHP 7, PHP 8)

mysqli::$connect_error — mysqli_connect_error — Возвращает описание последней ошибки подключения

Описание

Возвращает сообщение об ошибке последней попытки подключения.

Список параметров

У этой функции нет параметров.

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

Сообщение об ошибке. null , если ошибка отсутствует.

Примеры

Пример #1 Пример использования $mysqli->connect_error

/* @ используется для подавления предупреждений */
$mysqli = @new mysqli ( ‘localhost’ , ‘fake_user’ , ‘wrong_password’ , ‘does_not_exist’ );

if ( $mysqli -> connect_error ) <
/* Используйте предпочитаемый вами метод регистрации ошибок */
error_log ( ‘Ошибка при подключении: ‘ . $mysqli -> connect_error );
>
?>

/* @ используется для подавления предупреждений */
$link = @ mysqli_connect ( ‘localhost’ , ‘fake_user’ , ‘wrong_password’ , ‘does_not_exist’ );

if (! $link ) <
/* Используйте предпочитаемый вами метод регистрации ошибок */
error_log ( ‘Ошибка при подключении: ‘ . mysqli_connect_error ());
>
?>

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

  • mysqli_connect() — Псевдоним mysqli::__construct
  • mysqli_connect_errno() — Возвращает код ошибки последней попытки соединения
  • mysqli_errno() — Возвращает код ошибки последнего вызова функции
  • mysqli_error() — Возвращает строку с описанием последней ошибки
  • mysqli_sqlstate() — Возвращает код состояния SQLSTATE последней MySQL операции

Источник

mysqli::__construct

mysqli_connect

(PHP 5, PHP 7, PHP 8)

mysqli::__construct — mysqli::connect — mysqli_connect — Устанавливает новое соединение с сервером MySQL

Описание

Устанавливает соединение с работающим сервером MySQL.

Список параметров

Может быть либо именем хоста, либо IP-адресом. Предполагается использование локального хоста при указании в этом параметре null или строки «localhost». По возможности вместо протокола TCP/IP будут использоваться каналы. Протокол TCP/IP используется, если указаны и имя хоста и номер порта, например, localhost:3308 .

Если перед именем хоста задать строку p: , то будет открыто постоянное соединение. Если соединение открыто из пула подключений, будет автоматически вызвана функция mysqli_change_user() .

Имя пользователя MySQL.

Если не задан или равен null , MySQL-сервер в первую очередь попытается аутентифицировать пользователя в принципе имеющего пароль, а затем будет искать среди пользователей, у которых нет пароля. Такой подход позволяет одному пользователю назначать различные права (в зависимости от того, задан пароль или нет).

Если параметр задан, его значение будет использоваться в качестве имени базы данных по умолчанию при выполнении запросов.

Задаёт номер порта для подключения к серверу MySQL.

Задаёт сокет или именованный пайп, который необходимо использовать.

Передача параметра socket не будет явно задавать тип соединения при подключении к серверу MySQL. То, как будет устанавливаться соединение с MySQL-сервером, определяется параметром hostname .

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

mysqli::__construct() всегда возвращает объект, который представляет соединение с сервером MySQL, независимо от того, было оно успешным или нет.

mysqli_connect() возвращает объект, который представляет соединение с сервером MySQL или false в случае возникновения ошибки.

mysqli::connect() возвращает null в случае успешного выполнения или false в случае возникновения ошибки.

Ошибки

Если MYSQLI_REPORT_STRICT включена и во время подключения к базе данных произошла ошибка, выбрасывается mysqli_sql_exception .

Примеры

Пример #1 Пример использования mysqli::__construct()

/* Вы должны включить отчёт об ошибках для mysqli, прежде чем пытаться установить соединение */
mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );

$mysqli = new mysqli ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘my_db’ );

/* Установите желаемую кодировку после установления соединения */
$mysqli -> set_charset ( ‘utf8mb4’ );

printf ( «Успешно. %sn» , $mysqli -> host_info );
?>

/* Вы должны включить отчёт об ошибках для mysqli, прежде чем пытаться установить соединение */
mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );

$mysqli = mysqli_connect ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘my_db’ );

/* Установите желаемую кодировку после установления соединения */
mysqli_set_charset ( $mysqli , ‘utf8mb4’ );

printf ( «Успешно. %sn» , mysqli_get_host_info ( $mysqli ));

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

Пример #2 Расширение класса mysqli

class FooMysqli extends mysqli <
public function __construct ( $host , $user , $pass , $db , $port , $socket , $charset ) <
mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
parent :: __construct ( $host , $user , $pass , $db , $port , $socket );
$this -> set_charset ( $charset );
>
>

$db = new FooMysqli ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘my_db’ , 3306 , null , ‘utf8mb4’ );

Пример #3 Ручная обработка ошибок

Если отчёты об ошибках отключены, разработчик несёт ответственность за проверку и обработку ошибок

( 0 );
mysqli_report ( MYSQLI_REPORT_OFF );
$mysqli = new mysqli ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘my_db’ );
if ( $mysqli -> connect_errno ) <
throw new RuntimeException ( ‘ошибка соединения mysqli: ‘ . $mysqli -> connect_error );
>

/* Установите желаемую кодировку после установления соединения */
$mysqli -> set_charset ( ‘utf8mb4’ );
if ( $mysqli -> errno ) <
throw new RuntimeException ( ‘ошибка mysqli: ‘ . $mysqli -> error );
>

( 0 );
mysqli_report ( MYSQLI_REPORT_OFF );
$mysqli = mysqli_connect ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘my_db’ );
if ( mysqli_connect_errno ()) <
throw new RuntimeException ( ‘ошибка соединения mysqli: ‘ . mysqli_connect_error ());
>

/* Установите желаемую кодировку после установления соединения */
mysqli_set_charset ( $mysqli , ‘utf8mb4’ );
if ( mysqli_errno ( $mysqli )) <
throw new RuntimeException ( ‘ошибка mysqli: ‘ . mysqli_error ( $mysqli ));
>

Примечания

MySQLnd всегда подразумевает кодировку, которую использует по умолчанию сервер. Эта кодировка передаётся во время установки соединения/авторизации, которые использует mysqlnd.

Libmysqlclient по умолчанию использует кодировку, установленную в my.cnf или специальным вызовом mysqli_options() до использования mysqli_real_connect() , но после mysqli_init() .

Если используется Объектно-ориентированный стиль: Если соединение установить не удалось, метод всё равно вернёт объект. Проверить успешность создания подключения можно либо функцией mysqli_connect_error() или с помощью свойства mysqli->connect_error, как показано в примерах.

Если необходимо задать дополнительные параметры подключения, вроде времени ожидания и т.п., то вместо этого метода необходимо использовать функцию mysqli_real_connect() .

Вызов конструктора без параметров идентичен вызову функции mysqli_init() .

Ошибка «Can’t create TCP/IP socket (10106)» обычно означает, что директива конфигурации variables_order не содержит символ E . В Windows системах, если окружение не скопировано, переменная среды SYSTEMROOT будет недоступна, и у PHP возникнут проблемы с загрузкой Winsock.

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

  • mysqli_real_connect() — Устанавливает соединение с сервером mysql
  • mysqli_options() — Установка настроек
  • mysqli_connect_errno() — Возвращает код ошибки последней попытки соединения
  • mysqli_connect_error() — Возвращает описание последней ошибки подключения
  • mysqli_close() — Закрывает ранее открытое соединение с базой данных

User Contributed Notes 13 notes

That’s because since Windows 7, the hosts file doesn’t come with a preconfigured
127.0.0.1 localhost
anymore

So, if you notice a long connection creation, try «127.0.0.1» instead.

Please do use set_charset(«utf8») after establishing the connection if you want to avoid weird string issues. I do not know why the documentation does not warn you about this kind of stuff.

We had a hard time figuring out what was going on since we were using mb_detect_encoding and it said everything was UTF-8, but of course the display was wrong. If we used iconv from ISO-8859-1 to UTF-8 the strings looked fine, even though everything in the database had the right collation. So in the end, it was the connection that was the filter and although the notes for this function mention default charsets, it almost reads as a sidenote instead of a central issue when dealing with UTF and PHP/MySQL.

Just wanted to add a note for anyone looking to use the MySQLi persistent connections feature; it’s important to note that PHP opens and retains one connection per database user per process.

What this means is that if you are hosting multiple applications, each with its own database user (as is good practice) then you will end up multiplying the number of connections that PHP may hold open.

For example, if you have PHP configured with a maximum of eight worker processes, and you regularly use four different database users, then your MySQL server will need to accept at LEAST a maximum of 32 connections, or else it will run out.

However, if you would like to minimise the number of connections, what you can do is instead is to open the connection using a «guest» user (with no privileges except logging in) and then use ->change_user() to switch to a more privileged user, before switching back to the guest when you’re done. Since all of the connections would therefore belong to the guest user, PHP should only maintain one per worker process.

There’s a separate port parameter, unlike mysql_connect. However, using host:port on the host parameter does actually work.

There is a caveat. If the host is ‘localhost’ then the port is ignored, whether you use a port parameter or the implicit syntax I mentioned above. This is because ‘localhost’ will make it use unix sockets rather than TCP/IP.

If you want to connect via an alternate port (other than 3306), as you might when using an ssh tunnel to another host, using «localhost» as the hostname will not work.

Using 127.0.0.1 will work. Apparently, if you specify the host as «localhost», the constructor ignores the port specified as an argument to the constructor.

It should be noted that on PHP 7 (v7.0.2 at least), passing the empty string » for the Port argument while connecting to ‘localhost’ will prevent the connection from being successful altogether.

To work around this, use ‘null’.

public mysqli::__construct(
string $hostname = ini_get(«mysqli.default_host»),
string $username = ini_get(«mysqli.default_user»),
string $password = ini_get(«mysqli.default_pw»),
string $database = «»,
int $port = ini_get(«mysqli.default_port»),
string $socket = ini_get(«mysqli.default_socket»)
)

the mysqli construct looks at the Master PHP.ini values.
if you’re using a local ini overwrite of some sort add the ini_get to you’re php script:
$mysqli = new mysqli(ini_get(«mysqli.default_host»),ini_get(«mysqli.default_user»),ini_get(«mysqli.default_pw»))

If you get an error like
Can’t connect to MySQL server on ‘localhost’ (10061)
and you use named pipes/socket connections (or aren’t sure how you installed the MySQL server) try the following connect command:

( ‘.’ , $user_name , $password , $database_name , null , ‘mysql’ );
?>

The ‘.’ as hostname is absolutely necessary when using named pipes. ‘localhost’ won’t work. ‘mysql’ is the standard name for the pipe/socket.

A far more secure and language independent way of connecting to mysql is to use the READ_DEFAULT_FILE options. This passes the workload over to the mysql library, which allows for the configuration file itself to be outside of the scope of the language.

The config file itself is something like this:
[client]
user=user_u
password=user_password
host=dbhost
port=3306
database=the_database
default-character-set=utf8

The following code fragment (in OO mysql_i format)

$sqlconf=’/var/private/my.cnf’;
$sql = new mysqli;
$sql->init();
$sql->options(MYSQLI_READ_DEFAULT_FILE,$sqlconf);
$sql->real_connect();

A friend of mine encountered a sudden bug with CMS Piwigo. I discovered that :
— He had a hosting rule to use PHP 5.6.
— The hoster uses 5.6.6, verified using phpinfo();.
— The CMS declared a database name parameter as null.

That gallery CMS was unable to connect to MySQL and left only a warning message about it.

We tried to revert back to PHP 5.5, the CMS worked again.

Then we switched back to 5.6.6 and changed those lines :

$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket);

$dbname = »; // Use an empty string, not null

$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket);

So if you made the same mistake, using null where the manual invites to use an empty string, you should consider correcting your code.

mysqli can succeed in surprising ways, depending on the privileges granted to the user. For example,

GRANT USAGE ON *.* TO ‘myuser’@’localhost’ IDENTIFIED BY PASSWORD ‘mypassword’;
GRANT ALL PRIVILEGES ON `database_a`.* TO ‘myuser’@’localhost’;
CREATE DATABASE database_b;

= new mysqli ( ‘localhost’ , ‘myuser’ , ‘mypassword’ , ‘database_b’ );

if ( $db -> connect_error ) <
die( ‘Connect Error (‘ . $db -> connect_errno . ‘) ‘
. $mysqli -> connect_error );
>

printf ( «SQLSTATE: %sn» , $this -> db -> sqlstate );
printf ( «Warning Count: %sn» , $db -> warning_count );
$db -> close ();
?>

Will output:

SQLSTATE: 00000
Warning Count: 0

So, life is good — you’re connected to the database and executing mysqli methods. Except, life isn’t good, because you aren’t actually using database_b because myuser doesn’t have any privileges on it. You won’t catch this until you try to perform a later operation, when you’ll get an error, «MYSQL Error: No database selected», and find yourself scratching your head and thinking «what do you mean, of course I have a database selected; I selected one when I called the constructor».

As a result, you may want to perform an additional check after connecting to mysql, to confirm that you’re actually connected not just to the mysql server, but to the actual database:

= new mysqli ( ‘localhost’ , ‘myuser’ , ‘mypassword’ , ‘database_b’ );

if ( $db -> connect_error ) <
die( ‘Connect Error (‘ . $db -> connect_errno . ‘) ‘
. $mysqli -> connect_error );
> elseif ( $result = $db -> query ( «SELECT DATABASE()» )) <
$row = $result -> fetch_row ();
if ( $row [ 0 ] != ‘database_b’ ) <
//oops! We’re connected to mysql, but not to database_b
>
>
?>

Источник

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

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

Exceptions Are Bad Yet Awesome!

Sarfraz Ahmed
  
April 27, 2015 02:09 AM


Overview

At first thought, the words errors and exceptions give the general idea that they are the same thing or collectively errors especially to the beginners. For example, when we see this:

Fatal error: Call to undefined method Foo::bar()

Or this:

Exception: Method is not callable by this object

Most beginner developer would concluded that those are just errors that need to be fixed and that may be right in a superficial sense because both of those messages are bad and need to be fixed anyway but in reality they are different things. The first one is an Error while later one is an Exception. Once we understand there can be both errors and exceptions and how to successfully handle each, we can surely write better code.

In this post, we will see how we can deal with both of them and even create our own custom error and exception handlers for more control over how we want them to be displayed or handled while following best practices.

Difference between Errors and Exceptions

Errors

  • Errors are errors that are emitted by the programming language and you need to fix them.

  • There can be syntax errors or logic errors. In PHP, there are different levels of errors such as ERROR, PARSE, WARNING, NOTICE, STRICT. Some errors levels halt the further execution of your PHP script (such as FATAL errors) while others allow it to continue while presenting useful information that might also need to be fixed or payed attention to such as WARNING or NOTICE. And finally there are other error levels that can tell whether a particular function is deprecated (DEPRECATED) or whether or not standards are being followed (STRICT).

  • Errors can be converted into user-thrown exceptions while still some being recoverable other not because they are emitted by core programming language

  • We can emit custom/user errors through trigger_error() function

  • We can create custom error handler for all errors using set_error_handler()

  • The error_get_last function can be used to get any error that happened last in PHP code. The $php_errormsg variable can be used to get previous error message.

Exceptions:

  • Exceptions are object oriented approach to errors and are thrown intentionally by code/developer and should be handled/caught using try - catch -finally blocks

  • An Exceptionis a standard class that can be used like any other class and can also be extended.

  • Exceptions can have many types (through sub-classes) while errors can only have levels mentioned above.

  • Exceptions can be caught at any point in the call stack and can also be caught at root/default exception handler. In comparison, errors are only handled in pre-defined error handler.

  • We can throw custom/user exceptions by using throw new Exception(...)

  • We can create custom exception handler for all exceptions using set_exception_handler()

General Practice

Nowadays, it seems common (and better) practice to always throw exceptions (even for errors) from your code so that they can be caught and dealt with in caller script. Of course if we throw an exception for error which is FATAL, we can’t recover from it but we can still provide OOP approach to caller script. If you have used MySQL extension, you would notice that it emits normal errors if something goes wrong; here is an example when connection to database could not be made:

Warning: mysql_connect(): Access denied for user 'root'@'localhost'

Notice that it emits error level of Warning. This is just an example for the function mysql_connect but other functions of MySQL extension also emit errors in the same way and can be grabbed with mysql_error() function.

But if you use improved version of MySQL called MySQLi or even PDO, you would notice they can now also throw exceptions, here is same example if connection could not be made to database using mysqli:

mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');

It would give you both error as well as exception:

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user 'root'@'localhost'

mysqli_sql_exception: Access denied for user 'root'@'localhost' (using password: YES)

So these days any good written package or library or some extension you use, it would most likely generate Exceptions of its own type so that they can be caught and handled gracefully.

How Do Exceptions Help ?

Let’s understand through example. Let’s say you want to connect to database using mysql and you would normally do something like this:

mysql_connect('localhost', 'root', 'wrongPassword', 'test');

If connection could not be made to database, you would receive error:

Warning: mysql_connect(): Access denied for user 'root'@'localhost'

Now the only thing you can do is go to your code and edit it to specify correct database credentials.

Let’s now do the same thing using mysqli:

mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');

This would generate an error as well as exception as shown previously. Since exception is generated, we can catch it and show the message:

try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    echo $e->getMessage();
}

The reason why exception is useful here is because you are given a chance to catch that exception gracefully. Inside catch block, we can handle the exception however we want. For the sake of example, let’s say we want to connect to database again with correct password this time:

mysqli_report(MYSQLI_REPORT_STRICT);

try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    mysqli_connect('localhost', 'root', 'rightPassword', 'test');
}

And thanks to exception, we were able to catch it and handle it the way we needed and we are now connected to database which was simply not possible with previous example using mysql which only emitted an error and we couldn’t do much. Of course in real world applications, you might not have different passwords to connect to database but this example just gives an idea of how exceptions can be useful.

As another example, let’s say we want read feed/rss of some website using SimpleXML (which can also throw exceptions) and store 10 posts in an array:

$feedUrl = 'http://some_feed_url';
$feeds = file_get_contents($feedUrl);
$xml = new SimpleXmlElement($feeds);

$articles = array();
foreach ($xml->channel->item as $item) {
   $item = (array) $item;
   $articles[] = array('title' => $item['title'], 'link' => $item['link']);
}

$data['articles'] = array_slice($articles, 0, 10);

This would work as long as feed url is correct and has posts but if url is wrong, you would see a Fatal error as well Exception being generated by the script:

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML

Exception: String could not be parsed as XML

Since it is FATAL error, our script died at that point and we can’t do anything. How do we ensure that our script continues working and runs any code below that feed code even if provided feed url was wrong ? Of course we need to catch the exception since as we saw it also generated an Exception:

try {
    $feedUrl = 'http://some_feed_url';
    $feeds = file_get_contents($feedUrl);
    $xml = new SimpleXmlElement($feeds);

    $articles = array();
    foreach ($xml->channel->item as $item) {
       $item = (array) $item;
       $articles[] = array('title' => $item['title'], 'link' => $item['link']);
    }

    $data['articles'] = array_slice($articles, 0, 10);
} catch (Exception $e) {

}

echo 'Hello World';

And now since we have wrapped our code in try-catch and caught the exception, our code below that should still run. In this case even if feed url was wrong, you should still see the Hello World message. Our script didn’t die and continued its execution. So those two examples should now give idea of how useful exceptions can be when used.

How do I convert Errors into Exceptions?

To do so ,we can use the set_error_handler() function and throw exceptions of type ErrorException something like:

set_error_handler(function ($errorNumber, $errorText, $errorFile, $errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});

With that custom exception now in place, you can do things like:

try {
    // wrong url
    file_get_contents('http://wrong_url');
} catch (ErrorException $e) {
    // fix the url
    file_get_contents('http://right_url');
}

So in catch block, we are now able to fix the URL for the file_get_contents function. Without this exception, we could do nothing but may be suppressing the error by using error control operator @.

Universal Exception Handler

Now that we have seen how useful exceptions are and how to convert errors into exceptions, we can create our custom universal exception handler that can be used throughout the application. It will always generate exceptions not errors. It will do these things:

1 — Allow us to tell it our environment which can be either development or production

2 — In case of production environment, it will log all errors to a file instead of displaying them on screen

3 — In case of development environment, it will display all errors on the screen

/**
 * A class that handles both errors and exceptions and generates an Exception for both.
 *
 * In case of "production" environment, errors are logged to file
 * In case of "development" environment, errors are echoed out on screen
 *
 * Usage:
 *
 * new ExceptionHandler('development', '/myDir/logs');
 *
 * Note: Make sure to use it on very beginning of your project or bootstrap file.
 *
 */
class ExceptionHandler {
    // file path where all exceptions will be written to
    protected $log_file = '';
    // environment type
    protected $environment = '';

    public function __construct($environment = 'production', $log_file = 'logs')
    {
        $this->environment = $environment;
        $this->log_file = $log_file;

        // NOTE: it is better to set ini_set settings via php.ini file instead to deal with parse errors.
        if ($this->environment === 'production') {
            // disable error reporting
            error_reporting(0);
            ini_set('display_errors', false);
            // enable logging to file
            ini_set("log_errors", true);
            ini_set("error_log", $this->log_file);
        }
        else {
            // enable error reporting
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            // disable logging to file
            ini_set("log_errors", false);
        }

        // setup error and exception handlers
        set_error_handler(array($this, 'errorHandler'));
        set_exception_handler(array($this, 'exceptionHandler'));        
    }

    public function exceptionHandler($exception)
    {
        if ($this->environment === 'production') {
            error_log($exception, 3, $this->log_file);
        }

        throw new Exception('', null, $exception);
    }

    public function errorHandler($error_level, $error_message, $error_file, $error_line)
    {
        if ($this->environment === 'production') {      
            error_log($message, 3, $this->log_file);
        }

        // throw exception for all error types but NOTICE and STRICT
        if ($error_level !== E_NOTICE && $error_level !== E_STRICT) {
            throw new ErrorException($error_message, 0, $error_level, $error_file, $error_line);
        }        
    }
}

Test it:

// register our error and exceptoin handlers
new ExceptionHandler('development', 'logs');

// create error and exception for testing
trigger_error('Iam an error but will be converted into ErrorException!');
throw new Exception('I am an Exception anyway!');

So that is an example of basic universal error and exception handler class. Actually you can do a lot more like customizing the display of messages, getting the stack trace as well as code that caused it, creating timestamp for when those events take place, etc. You should checkout the official documentation in order to achieve those goodies. At any point in your code, you want to restore original PHP’s error and exception handlers, you can use restore_error_handler() and restore_exception_handler() functions.

Conclusion

No exception to exceptions!


As a side note, I personally hope someday a PSR standard is created for handling errors and exceptions and their best practices because they are integral part of any PHP code.

Правильная обработка ошибок позволяет сделать стабильное приложение, которое не будет завершаться неожиданно. В случае возникновения непредвиденной ситуации программа должна выдавать вменяемый ответ, почему она не хочет исполнится. И создание правильного механизма обработки ошибок — это задача программиста.

В этой статье рассмотрим два вида ошибок, которые могут возникнуть при программировании взаимодействия с базой данных. Первый тип — это ошибка подключения к базе данных. Второй тип — это ошибка выполнения запроса к базе данных. Для обработки этих ошибок будем использовать специальные функции для работы с базой.

Ошибка соединения с базой данных

Сразу приведём пример обработки ошибки с соединением с базой данных:

<?php 
   $host = 'localhost'; // адрес сервера
   $db_name = 'database'; // имя базы данных
   $user = 'user'; // имя пользователя
   $password = 'password'; // пароль

   // создание подключения к базе   
      $connection = mysqli_connect($host, $user, $password, $db_name);

   // проверка правильности подключения
      if(!$connection){ // при соединении с базой данных возникла ошибка
         echo 'Ошибка соединения: ' . mysqli_connect_error() . '<br>';
         echo 'Код ошибки: ' . mysqli_connect_errno();
      }else{ // соединение было установлено успешно
         // здесь можно делать запрос к базе, 
         // потому что соединение успешно установлено
      }
?>

В этом примере можно заметить функцию mysqli_connect_error. Она выводит текстовое описание ошибки подключения (на английском языке). В отличии от неё функция mysqli_connect_errno выводит числовой код ошибки, к примеру «1045».

Ошибка запроса к базе

Теперь попробуем доработать пример из предыдущего параграфа и добавить запрос к базе данных. Не будем вдаваться в детали, что будет записано в тексте SQL запроса, просто предположим, что он может завершиться ошибкой. К примеру, из-за неожиданного отключения сервера с базой данных от сети. В примере добавим проверку на наличие ошибок при выполнении запроса:

<?php 
   $host = 'localhost'; // адрес сервера
   $db_name = 'database'; // имя базы данных
   $user = 'user'; // имя пользователя
   $password = 'password'; // пароль

   // создание подключения к базе   
      $connection = mysqli_connect($host, $user, $password, $db_name);

      if(!$connection){ // проверка правильности подключения
         echo 'Ошибка соединения: ' . mysqli_connect_error() . '<br>';
         echo 'Код ошибки: ' . mysqli_connect_errno();
      }else{ // подключение успешно установлено

         // текст SQL запроса, который будет передан базе
            $query = 'SELECT * FROM `USERS`';

         // выполняем запрос к базе данных
            $result = mysqli_query($connection, $query);

            if(!$result){ // запрос завершился ошибкой
               echo 'Ошибка запроса: ' . mysqli_error($connection) . '<br>';
               echo 'Код ошибки: ' . mysqli_errno($connection);
            }else{ // запрос успешно выполнился
               while($row = $result->fetch_assoc()){
                  // обрабатываем полученные данные
               }
            }
         // закрываем соединение с базой
            mysqli_close($connection);
      }
?>

В этом примере есть две функции, которые работают с ошибками базы. Функция mysqli_error возвращает описание ошибки запроса (на английском языке), а функция mysqli_errno возвращает числовой код ошибки, к примеру, «1193».

Обратите внимание, что все функции обработки ошибок в этой статье (mysqli_connect_error, mysqli_connect_errno, mysqli_error, mysqli_errno) возвращают информацию только о последней ошибке. Но ошибок может быть несколько.

Была ли статья полезной?

Была ли эта статья полезна?

Есть вопрос?

хостинг для сайтов

Закажите недорогой хостинг

Заказать

всего от 290 руб

Понравилась статья? Поделить с друзьями:
  • Mysqli error 500
  • Mysqli error 1054
  • Mysqli connect php error
  • Mysqli connect error 2002 no such file or directory
  • Mysqldump got error 2003