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

За последние 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

Содержание

  1. mysqli::$error — Возвращает строку с описанием последней ошибки
  2. mysqli_error
  3. Описание
  4. Список параметров
  5. Возвращаемые значения
  6. Примеры
  7. Смотрите также
  8. How to report errors in mysqli
  9. Introduction
  10. What to do with the error message you get?
  11. Related articles:
  12. Got a question?
  13. SEE ALSO:
  14. Latest comments:
  15. Add a comment
  16. Comments:
  17. Reply:
  18. Reply:
  19. mysqli::$error
  20. Description
  21. Parameters
  22. Return Values
  23. Examples
  24. See Also
  25. User Contributed Notes 7 notes

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

mysqli_error

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

Описание

Возвращает сообщение об ошибке последнего вызова функции MySQLi, который может успешно выполниться или провалиться.

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

Только для процедурного стиля: Идентификатор соединения, полученный с помощью mysqli_connect() или mysqli_init()

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

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

Примеры

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

= 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 ();
?>

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

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

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

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

Источник

How to report errors in mysqli

Add the following line before mysqli_connect() (or new mysqli() ):

Introduction

Reporting errors is the most essential thing in programming. A programmer is effectively deaf-blind if they cannot see errors occurred during the script execution. So it is very important to configure error reporting for your code properly, including database interactions.

By default, when you are running mysqli_query() or — preferably — prepare()/bind()/execute() , mysqli will just silently return false if a query fails, telling you nothing of the reason.

You’ll notice the error only when the following command, when trying to use the query result, will raise an error, such as

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.

Unfortunately, this error message tells you nothing of the actual problem. It just bluntly says that your query failed, and nothing else.

It happens because by default mysqli is configured to remain silent if a query returned an error. So you can tell that’s an extremely inconvenient behavior.

Luckily, mysqli can be configured to throw a PHP exception in case of a mysql error. It means that a PHP error will be thrown automatically every time a query returns an error, without any effort on your part!

Let’s see a small demonstration:

And run your script again. Whoa! An error appears in a puff of smoke, explaining what was the problem:

As you can see, this is quite a detailed information, including the erroneous part of the query, and even a stack trace that helps you to find a particular function that called the erroneous query.

So again: just make sure that you always have this magic line before mysqli_connect() in all your scripts:

What to do with the error message you get?

It should be a knee-jerk reflex to copy and paste the error message in Google search. It will lead you to several Stack Overflow questions related to this particular problem with many answers with solutions.

However, there is another possibility. You can try to actually read the error message you get. Usually, the error message explains it pretty straightforward, what is the error. However, some errors could be cryptic. You have to understand some considerations used in Mysql error messages:

  • in case of a syntax error, the cited query part begins right after the error.
  • it means that, therefore, if the error is at the very end of the query, the cited query part would be an empty string. Most likely it happens when you add a variable directly to the query and this variable happen to be empty (yet another reason to use prepared statements as they will make such errors just impossible to appear.

Related articles:

Got a question?

I am the only person to hold a gold badge in , and on Stack Overflow and I am eager to show the right way for PHP developers.

Besides, your questions let me make my articles even better, so you are more than welcome to ask any question you have.

SEE ALSO:

  • 05.01.23 10:15
    Ayuba for Mysqli prepared statement with multiple values for IN clause:
    I have bn learning php but still finding it difficult to handle a project can u put me throughplease
    read more
  • 04.01.23 19:55
    Anjana for (The only proper) PDO tutorial:
    Hello, I have a query regarding PDO and MySQLi. I am creating a project in PHP and I have used.
    read more
  • 03.01.23 15:21
    Mange for Do generators really reduce the memory usage? :
    In your `while`-example, shouldn’t `if ($item % 2 === 0 )` be `if ($num % 2 === 0 )`?
    read more
  • 02.01.23 07:23
    Vern for How to execute 1000s INSERT/UPDATE queries with PDO?:
    Is the 9th line correct? An INSERT with a SET in the same statement?
    read more
  • 30.12.22 07:30
    Seraphina for Mysqli prepared statement with multiple values for IN clause:
    This article accurately and concisely solved the problem that was bugging me for ages. Thank you.
    read more

Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator’s review.

Markdown is now supported:

  • > before and an empty line after for a quote
  • four spaces to mark a block of code

bind_param() seems not to throw an exception, only errors. what do you advice us to do in this case?

Reply:

That’s an interesting question. The simplest solution would be to upgrade the PHP version. Starting from 8.0 bind_param is throwing exceptions all right.

For the older versions, it depends on what you need the exception for. Normally, there should be no difference: a Warning as in error all the same, it will be reported and the next call to execute will halt the code execution.

But if you really need and exception, you can add a simple error handler to your code that would convert all errors to excepions, like

Hope some of these suggestions will help. If not, then please let me know.

a bit misleading if all you have to do is call mysqli_error() and mysqli_errno() no need to reconfigure anything.

Reply:

There are two problems with this mindset.

First, the logic is somewhat inverted here: as long as you have to run only one SQL query, there is not much difference. But even with a dozen, not to mention hundreds of SQL queries, this «call mysqli_error() and mysqli_errno()» after every query becomes «a bit misleading». Now compare it with just «reconfiguring» a single line of code.

Second, the question is, what you’re going to do with all these mysqli_error() and mysqli_errno() calls. Are you sure you are going to use them properly? And what if some day you will decide to change that behavior? For example, now you want to die() with the error message but eventually you will learn that it’s just gross and it needs to be changed. So, which approach will make it simpler: when you have just a single place where error reporting is configured, or when you have dozens to hundreds places where you need to rewrite the code?

Источник

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

Источник

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

Понравилась статья? Поделить с друзьями:
  • Mysqli error не выводит ошибку
  • Mysqli error no database selected
  • Mysqli error log
  • Mysqli error exception
  • Mysqli error 500