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

Содержание

  1. mysqli::$error — Возвращает строку с описанием последней ошибки
  2. mysqli_error
  3. Описание
  4. Список параметров
  5. Возвращаемые значения
  6. Примеры
  7. Смотрите также
  8. mysqli::$error
  9. Описание
  10. Список параметров
  11. Возвращаемые значения
  12. Примеры
  13. Смотрите также
  14. User Contributed Notes 7 notes
  15. mysql_error
  16. Description
  17. Parameters
  18. Return Values
  19. Examples
  20. See Also
  21. User Contributed Notes 14 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 операции

Источник

mysqli::$error

(PHP 5, PHP 7, PHP 8)

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

Описание

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

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

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

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

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

Примеры

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

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

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

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

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

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

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

Источник

mysql_error

mysql_error — Returns the text of the error message from previous MySQL operation

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

Description

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno() ), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the error text from the last MySQL function, or » (empty string) if no error occurred.

Examples

Example #1 mysql_error() example

= mysql_connect ( «localhost» , «mysql_user» , «mysql_password» );

mysql_select_db ( «nonexistentdb» , $link );
echo mysql_errno ( $link ) . «: » . mysql_error ( $link ). «n» ;

mysql_select_db ( «kossu» , $link );
mysql_query ( «SELECT * FROM nonexistenttable» , $link );
echo mysql_errno ( $link ) . «: » . mysql_error ( $link ) . «n» ;
?>

The above example will output something similar to:

See Also

  • mysql_errno() — Returns the numerical value of the error message from previous MySQL operation
  • » MySQL error codes

User Contributed Notes 14 notes

If you want to display errors like «Access denied. «, when mysql_error() returns «» and mysql_errno() returns 0, use $php_errormsg. This Warning will be stored there. You need to have track_errors set to true in your php.ini.

Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says: «Errors coming back from the MySQL database backend no longer issue warnings.» Which is not true.

Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.

Just spent a good 30 minutes trying to figure out why i didn’t see my SQL errors.

Using a manipulation of josh ><>‘s function, I created the following. It’s purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman’s escape_data() as well since I use it in q().

function escape_data ( $data ) <
global $dbc ;
if( ini_get ( ‘magic_quotes_gpc’ )) <
$data = stripslashes ( $data );
>
return mysql_real_escape_string ( trim ( $data ), $dbc );
>

function q ( $page , $query ) <
// $page
$result = mysql_query ( $query );
if ( mysql_errno ()) <
$error = «MySQL error » . mysql_errno (). «: » . mysql_error (). «n
When executing:
n $query n
» ;
$log = mysql_query ( «INSERT INTO db_errors (error_page,error_text) VALUES (‘ $page ‘,’» . escape_data ( $error ). «‘)» );
>
>

// Run the query using q()
$query = «INSERT INTO names (first, last) VALUES (‘myfirst’, ‘mylast’» );
$result = q ( «Sample Page Title» , $query );
?>

When creating large applications it’s quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.

This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.

The script writes a log file in directory ( in this case /log ) as well.

The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.

$system_operator_mail = ‘developer@company.com’ ;
$system_from_mail = ‘info@mywebsite.com’ ;

function db_query ( $query ) <
global $b_debugmode ;

// Perform Query
$result = mysql_query ( $query );

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (! $result ) <
if( $b_debugmode ) <
$message = ‘Invalid query:
‘ . mysql_error () . ‘

raise_error ( ‘db_query_error: ‘ . $message );
>
return $result ;
>

function raise_error ( $message ) <
global $system_operator_mail , $system_from_mail ;

$serror =
«Env: » . $_SERVER [ ‘SERVER_NAME’ ] . «rn» .
«timestamp: » . Date ( ‘m/d/Y H:i:s’ ) . «rn» .
«script: » . $_SERVER [ ‘PHP_SELF’ ] . «rn» .
«error: » . $message . «rnrn» ;

// open a log file and write error
$fhandle = fopen ( ‘/logs/errors’ . date ( ‘Ymd’ ). ‘.txt’ , ‘a’ );
if( $fhandle ) <
fwrite ( $fhandle , $serror );
fclose (( $fhandle ));
>

// e-mail error to system operator
if(! $b_debugmode )
mail ( $system_operator_mail , ‘error: ‘ . $message , $serror , ‘From: ‘ . $system_from_mail );
>

My suggested implementation of mysql_error():

$result = mysql_query($query) or die(«A fatal MySQL error occured.n
Query: » . $query . «
nError: (» . mysql_errno() . «) » . mysql_error());

This will print out something like.

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It’s very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn’t let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

When dealing with user input, make sure that you use
echo htmlspecialchars ( mysql_error ());
?>
instead of
echo mysql_error ();
?>

Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.

Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?

some error can’t handle. Example:

ERROR 1044: Access denied for user: ‘ituser@mail.ramon.intranet’ to database ‘itcom’

This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = «» .

«Errors coming back from the MySQL database backend no longer issue warnings.» Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host ‘locallllllhost’ (11001)

That’s a warning, which is not trapped by mysql_error()!

My suggested implementation of mysql_error():

$result = mysql_query($query) or die(«A fatal MySQL error occured.n
Query: » . $query . «
nError: (» . mysql_errno() . «) » . mysql_error());

This will print out something like.

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It’s very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn’t let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Oops, the code in my previous post only works for queries that don’t return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):

function myquery ($query) <
$result = mysql_query($query);
if (mysql_errno())
echo «MySQL error «.mysql_errno().»: «.mysql_error().»n
When executing:
n$queryn
«;
return $result;
>

This is a big one — As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I’m still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():

MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client

According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:

Set PASSWORD for ‘user’@’host’ = OLD_PASSWORD(‘password’);

Источник

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

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

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

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

<?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 руб

I have a mysqli query that wont execute and I would like to display information about why that’s happening. Im just fooling around with this example but I imagine something like this:

$myQuery= $mysqli->query("UPDATE table SET id = 1 WHERE id = 3");
if(!$myQuery) //If query couldnt be executed
{
echo $mysqli->error; //Display information about why wasnt executed (eg. Error: couldnt find table)
}

asked Apr 10, 2017 at 4:49

nightlynutria's user avatar

1

try using

// Perform a query, check for error
if (!mysqli_query($con,"UPDATE table SET id = 1 WHERE id = 3"))
{
 echo("Error description: " . mysqli_error($con));
}

mysqli_close($con);

answered Apr 10, 2017 at 4:53

Nishant Nair's user avatar

Nishant NairNishant Nair

1,9891 gold badge13 silver badges18 bronze badges

0


Definition and Usage

The mysqli_error() function returns the description of the error occurred during the last MySQLi function call.

Syntax

mysqli_error($con)

Parameters

Sr.No Parameter & Description
1

con(Mandatory)

This is an object representing a connection to MySQL Server.

Return Values

PHP mysqli_error() function returns an string value representing the description of the error from the last MySQLi function call. If there are no errors this function returns an empty string.

PHP Version

This function was first introduced in PHP Version 5 and works works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_error() function (in procedural style) −

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to retrieve all the rows of employee table
   mysqli_query($con, "SELECT * FORM employee");

   //Error
   $error = mysqli_error($con);
   print("Error Occurred: ".$error);

   //Closing the connection
   mysqli_close($con);
?>

This will produce following result −

Error Occurred: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FORM employee' at line 1

Example

In object oriented style the syntax of this function is $con ->error. Following is the example of this function in object oriented style −

<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   //Query to retrieve all the rows of employee table
   $con -> query("SELECT * FROM wrong_table_name");

   //Error 
   $error = $con ->error;
   print("Error Occurred: ".$error);

   //Closing the connection
   $con -> close();
?>

This will produce following result −

Error Occurred: Table 'mydb.wrong_table_name' doesn't exist

Example

Following is another example of the mysqli_error() function −

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to SELECT all the rows of the employee table
   mysqli_query($con, "SELECT * FROM employee");
   print("Errors in the SELECT query: ".mysqli_error($con)."n");

   //Query to UPDATE the rows of the employee table
   mysqli_query($con, "UPDATE employee set INCOME=INCOME+5000 where FIRST_NAME in (*)");
   print("Errors in the UPDATE query: ".mysqli_error($con)."n");

   //Query to INSERT a row into the employee table
   mysqli_query($con, "INSERT INTO employee VALUES (Archana, 'Mohonthy', 30, 'M', 13000, 106)");
   print("Errors in the INSERT query: ".mysqli_error($con)."n");
  
   //Closing the connection
   mysqli_close($con);
?>

This will produce following result −

Errors in the SELECT query:
Errors in the UPDATE query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)' at line 1
Errors in the INSERT query: Unknown column 'Archana' in 'field list'

Example

<?php
   $connection_mysql = mysqli_connect("localhost","root","password","mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   if (!mysqli_query($connection_mysql,"INSERT INTO employee (FirstName) VALUES ('Jack')")){
      echo("Error description: " . mysqli_error($connection_mysql));
   }
   
   mysqli_close($connection_mysql);
?>

This will produce following result −

Error description: Unknown column 'FirstName' in 'field list'

php_function_reference.htm

Last update on August 19 2022 21:50:40 (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 часа нас посетили 11616 программистов и 1162 робота. Сейчас ищут 411 программистов …

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

mysqli_error

(PHP 5, PHP 7, PHP 8)

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

Description

Object-oriented style

Procedural style

mysqli_error(mysqli $mysql): string

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

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


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

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


$mysqli->close();
?>

Procedural style

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


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


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

How to write SQL using PHP to handle the data in MySQL database? In any database
driven script we have to update, add, modify, data in the tables. By using PHP
we can do all this using different functions available in PHP. We will start
with very basic function, which will execute any query written in sql and can be
applied to MySQL database.

SQL

Structured Query Language or popularly known as SQL is an universal language to handle
database. An introduction and different types of sql command like select,
insert, update etc you will get in the sql section of this site. There are some
advance SQL commands like left join, linking of tables etc to study. If you are
not comfortable with SQL any time you can refer the materials in sql section.

There are three steps involved in this process.

  1. Connection to database
  2. Build the query and execute
  3. Display the data

Connecting database and executing Query

To manage data we have to connect to MySQL database and execute query to get our date. Here there are two ways to use PHP drivers to connect to MySQL and execute the functions for getting records.

One is using Portable Data Object ( PDO )
Second one is MySQLI ( MysQL Improved )

PHP Functions & SQL

Let us start with the function required to execute one query in PHP. Once you have connection established then we can execute sql command by using PHP function mysql_query(). Here is the syntax of the function.

Let us first write the query and store in a variable. We will write a query to
create table.

$query="CREATE TABLE student ( id int(2) NOT NULL auto_increment, name varchar(50) NOT NULL
default '', class varchar(10) NOT NULL default '', mark int(3) NOT NULL default
'0', PRIMARY KEY (id) ) TYPE=MyISAM";

We have stored the sql create query in a variable $query and we will pass this as a
parameter to the function like below.

$rt=$connection->query($query);

The above command will execute php_mysqli() the query ( stored in variable $query) and we can
check the status of the query ( successful or not ) by checking the value of the variable $rt. $rt will be true if the query is successfully executed or it will return false. We will use php if command to check the status of the query.

if($rt){echo " Command is successful ";}
else
{echo "Command is not successful ";}

So from the above line we can know that the query has worked or failed. But we will
not come to know about the error if the database has some error and the query has failed. To get the error
message we have to use another function mysqli_error() to print the error message
returned by MySQL database after executing the query. Here it is how to print
the error message.

echo mysqli_error();

The above line will print the error returned by mysql database if the query fails to
execute. You can read more on mysql error here.  

The
complete code is available below.

$query="UPDATE  student SET class='Five'";
if ($connection->query($query)) {
echo "Records Updated";
}else{
echo $connection->error;
}

Before executing the above code we must connect to mysql database by using mysqli connection string.

Subscribe

* indicates required

Email Address *

First Name

Last Name

Subscribe to plus2net

    plus2net.com

    PHP MySQL Data Display

    PHP functions to execute query to manage database, tables & records

    PHP MySql Data Display

    Displaying details of record on click by user

    Displaying record details with edit option

    Displaying one record in a page with all details

    Displaying records without repetitions of same field data

    PHP Paging or breaking records per page

    vexatiousjones

    04-02-2016

    Im getting a No Database Selected error when using this code. Im using PDO connection string linked aboe. Any Suggestions?
    smo1234

    06-02-2016

    YOu need to connect to database and select database. Read the connection string link available here.
    Ann Ekpe

    26-03-2017

    Good day . please I need your assistance.I am currently designing a webpage with members signing in and having a dashboard.I want to be able to send data from the database to each particular member , so anytime they login to the website they can view the data… Urgent HELP
    smo1234

    26-03-2017

    You can store the message in a table and display inside login area, that is when member login is completed this message can be displayed. The message can be managed by adding or updating new message etc.
    Knowledge of any scripting language and Database handling is required.

    Post your comments , suggestion , error , requirements etc here .

    Detail

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Eberspacher hydronic d5wz сброс ошибок
  • Eberspacher error как посмотреть код ошибки
  • Eberspacher d4ws ошибка 31
  • Eberspacher airtronic d2 24v коды ошибок
  • Eberspacher 052 ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии