Mysql вывод ошибок php

(PHP 4, PHP 5)

mysql_errorВозвращает текст ошибки последней операции с MySQL

Описание

mysql_error(resource $link_identifier = NULL): string

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

link_identifier

Соединение MySQL. Если идентификатор соединения не был указан,
используется последнее соединение, открытое mysql_connect(). Если такое соединение не было найдено,
функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров.
Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING.

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

Возвращает текст ошибки выполнения последней функции MySQL,
или '' (пустую строку), если операция
выполнена успешно.

Примеры

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

<?php
$link
= 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";
?>

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

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

aleczapka _at) gmx dot net

19 years ago

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.

Pendragon Castle

14 years ago

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

<?php

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<br>When executing:<br>\n$query\n<br>";

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

?>

Florian Sidler

13 years ago

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.

l dot poot at twing dot nl

17 years ago

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.

Regars,

Lennart Poot
http://www.twing.nl

<?php
$b_debugmode
= 1; // 0 || 1$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 = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
$message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
die(
$message);
}
raise_error('db_query_error: ' . $message);
}
return
$result;
}

function

raise_error( $message ){
global
$system_operator_mail, $system_from_mail;$serror=
"Env: " . $_SERVER['SERVER_NAME'] . "\r\n" .
"timestamp: " . Date('m/d/Y H:i:s') . "\r\n" .
"script: " . $_SERVER['PHP_SELF'] . "\r\n" .
"error: " . $message ."\r\n\r\n";// 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 );
}
?>

Anonymous

22 years ago

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 = "" .

Anonymous

18 years ago

My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\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.

Good luck,

-Scott

olaf at amen-online dot de

19 years ago

When dealing with user input, make sure that you use
<?php
echo htmlspecialchars (mysql_error ());
?>
instead of
<?php
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?

josh ><>

19 years ago

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<br>When executing:<br>\n$query\n<br>";
return $result;
}

Gianluigi_Zanettini-MegaLab.it

16 years ago

A friend of mine proposed a great solution.

<?php
$old_track
= ini_set('track_errors', '1');

.....

if (

$this->db_handle!=FALSE && $db_selection_status!=FALSE)
{
$this->connected=1;
ini_set('track_errors', $old_track);
}
else
{
$this->connected=-1;
$mysql_warning=$php_errormsg;
ini_set('track_errors', $old_track);
throw new
mysql_cns_exception(1, $mysql_warning . " " . mysql_error());
}
?>

scott at rocketpack dot net

20 years ago

My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

<b>A fatal MySQL error occured</b>.
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.

Good luck,

-Scott

Gianluigi_Zanettini-MegaLab.it

16 years ago

"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()!

phpnet at robzazueta dot com

16 years ago

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

This saved my hide.

miko_il AT yahoo DOT com

19 years ago

Gerrit

9 years ago

The following code returns two times the same error, even though I would have expected only one:

$ conn = mysql_connect ('localhost', 'root', '');
$ conn2 = mysql_connect ('localhost', 'root', '');

mysql_select_db ('db1', $ conn);
mysql_select_db ('db2', $ conn2);

$ result = mysql_query ("select 1 from dual", $ conn);
$ result2 = mysql_query ("select 1 from luad", $ conn2);

echo mysql_error ($ conn) "<hr>".
echo mysql_error ($ conn2) "<hr>".

The reason for this is that mysql_connect not working as expected a further connection returns. Since the parameters are equal, a further reference to the previous link is returned. So also changes the second mysql_select_db the selected DB of $conn to 'db2'.

If you change the connection parameters of the second connection to 127.0.0.1, a new connection is returned. In addition to the parameters new_link the mysql_connect() function to be forced.

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("Соединение не удалось: %s\n", $mysqli->connect_error);
exit();
}

if (!

$mysqli->query("SET a=1")) {
printf("Сообщение ошибки: %s\n", $mysqli->error);
}
/* Закрыть соединение */
$mysqli->close();
?>

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

<?php
$link
= mysqli_connect("localhost", "my_user", "my_password", "world");/* Проверить соединение */
if (mysqli_connect_errno()) {
printf("Соединение не удалось: %s\n", mysqli_connect_error());
exit();
}

if (!

mysqli_query($link, "SET a=1")) {
printf("Сообщение ошибки: %s\n", mysqli_error($link));
}
/* Закрыть соединение */
mysqli_close($link);
?>

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

Сообщение ошибки: Unknown system variable 'a'

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

  • 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: %s\n", $mysqli->error);
}
?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
<?php
$query
= "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!

$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}
?>

This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:\database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

<?php
mysqli_report
(MYSQLI_REPORT_OFF); //Turn off irritating default messages$mysqli = new mysqli("localhost", "my_user", "my_password", "world");$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (

$mysqli->error) {
try {
throw new
Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
} catch(
Exception $e ) {
echo
"Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
echo
nl2br($e->getTraceAsString());
}
}
//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table

#0 G:\\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:\data\WorkSites\1framework5\tests\dbtest.php(29): database->getString('SELECT XXname F...')
#2 c:\PHP\includes\simpletest\runner.php(58): testOfDB->testGetVal()
#3 c:\PHP\includes\simpletest\runner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:\PHP\includes\simpletest\runner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:\PHP\includes\simpletest\runner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:\PHP\includes\simpletest\simple_test.php(90): SimpleRunner->run()
#7 c:\PHP\includes\simpletest\simple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:\PHP\includes\simpletest\simple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:\all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.

se (at) brainbits (dot) net

17 years ago

The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

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

you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:

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

callforeach at gmail dot com

8 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

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

abderrahmanekaddour dot aissat at gmail dot com

1 year 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);
?>

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:\classfiles\lib5\database.php(214): mysqli->query('select sess_val...')
#1 G:\classfiles\lib5\Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:\classfiles\includes.php(50): session_start()
#4 G:\tests\all_tests.php(4): include('G:\data\WorkSit...')
#5 {main}

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

i am unable to get the last 2 echos to work, even if the update query fails it still displays success. If anyone has any suggestions on this code to be improved on any line, please do!

<?php
        if(!empty($_POST['username']) && !empty($_POST['answer']))  { 
            $username = $_POST['username'];
            $idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
            or die(mysql_error());
            $fetched = mysql_fetch_array($idfetch);  
            $id = $fetched['id']; //get users id for checking
            $answer = $_POST['answer'];
            $password = (mysql_real_escape_string($_POST['password']));
            $confpass = (mysql_real_escape_string($_POST['confpass']));
            if ($password != $confpass) {
                echo ("Passwords do not match, please try again.");
                exit;
            }
            $updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
            if($updatequery)  {  
                echo "<h1>Success</h1>";  
                echo "<p>Your account password was successfully changed. Please <a href=\"login.php\">click here to login</a>.</p>";  
            }  
            else  {  
                echo "<h1>Error</h1>";  
                echo "<p>Sorry, but a field was incorrect.</p>";  
            }  
       } 
?>

Thanks in advance!

Sterling Archer's user avatar

asked Dec 17, 2012 at 6:34

sparkones's user avatar

4

mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error()."update failed");

and use

mysql_affected_rows()

Returns the number of affected rows on success, and -1 if the last query failed.

answered Dec 17, 2012 at 6:48

Arun Killu's user avatar

Arun KilluArun Killu

13.6k5 gold badges34 silver badges61 bronze badges

use try catch and try to get the error enable error reporting in php also

<?php
        error_reporting(E_ALL);
        ini_set('display_errors','On');
        if(!empty($_POST['username']) && !empty($_POST['answer']))  { 
        $username = $_POST['username'];
        $idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
        or die(mysql_error());
        $fetched = mysql_fetch_array($idfetch);  
        $id = $fetched['id']; //get users id for checking
        $answer = $_POST['answer'];
        $password = (mysql_real_escape_string($_POST['password']));
        $confpass = (mysql_real_escape_string($_POST['confpass']));
        if ($password != $confpass) {
        echo ("Passwords do not match, please try again.");
        exit;}

        try{
        $updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
        if($updatequery)  {  
        echo "<h1>Success</h1>";  
        echo "<p>Your account password was successfully changed. Please <a href=\"login.php\">click here to login</a>.</p>";  }  
        else  {  
        echo "<h1>Error</h1>";  
        echo "<p>Sorry, but a field was incorrect.</p>";  
        }  

        }catch(Exception $e){
            print_R($e);
        }
        }

answered Dec 17, 2012 at 6:40

Akhilraj N S's user avatar

Akhilraj N SAkhilraj N S

9,0595 gold badges36 silver badges43 bronze badges

use or die(mysql_error()) as it will display mysql error if there is an error with your query.

$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error());

answered Dec 17, 2012 at 6:38

sicKo's user avatar

sicKosicKo

1,2411 gold badge12 silver badges35 bronze badges

Try this:

$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'");
if(!idfetch){
  die(mysql_error());
}

Do the same for all other queries too.

answered Dec 17, 2012 at 6:43

Chetana Kestikar's user avatar

try this, first count the row count value its great 1 then proceed the login process.

<?php
    if(!empty($_POST['username']) && !empty($_POST['answer']))  { 
        $username = $_POST['username'];
        $idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
        or die(mysql_error());
        $fetched = mysql_fetch_array($idfetch);

        $count= mysql_num_rows($idfetch);

        if($count>0){
        $id = $fetched['id']; //get users id for checking
        $answer = $_POST['answer'];
        $password = (mysql_real_escape_string($_POST['password']));
        $confpass = (mysql_real_escape_string($_POST['confpass']));
        if ($password != $confpass) {
            echo ("Passwords do not match, please try again.");
            exit;
        }

        $updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");

          if($updatequery)  {  
            echo "<h1>Success</h1>";  
            echo "<p>Your account password was successfully changed. Please <a href=\"login.php\">click here to login</a>.</p>";  
         }  
           else  {  
             echo "<h1>Error</h1>";  
             echo "<p>Sorry, but a field was incorrect.</p>";  
           }  
   } } ?>

answered Dec 17, 2012 at 6:48

RaJeSh's user avatar

RaJeShRaJeSh

3133 silver badges14 bronze badges

Use

if(mysql_num_rows($updatequery)  > 0) {
    // success
} else {
    // error
}

$updatequery will always be true (not NULL), until there is an error in your query

answered Dec 17, 2012 at 6:36

Stefan Fandler's user avatar

2

Функции вывода информации об ошибках в MySQLiПриветствую всех читателей!  Сегодня я хочу вам рассказать про функции вывода ошибок, которые используются в MySQLi. Бывают такие моменты, что запрос к базе завершается ошибкой, и ошибка выводится на экран не в обычном виде. То есть ошибка ссылается просто на строку в файле php, в котором происходит этот запрос к базе. Вот как раз для вывода нормальной информации об ошибках и используются функции MySQLi.

И так приступим. ;)

За предоставление информации об ошибках, в MySQLi используются функции mysqli_errno и mysqli_error. Но эти функции не используются для получения информации об ошибках, возникших в функции соединения с базой данных. То есть эти функции можно использовать только для выявления ошибок, которые возникают в выполнении запросов к базе, больше на http://makarou.com/mysqli-%E2%80%93-novaya-versiya-rasshireniya-mysql.

Синтаксис этих функций выглядит следующим образом:

mysqli_error($load);
mysqli_errno($load);

Как можно заметить, функции принимают только одно значение – это идентификатор соединения с базой данных. Функция mysqli_error – показывает запрос, который завершился ошибкой. А функция mysqli_errno – показывает код ошибки.

Если ошибка возникает в функции подключения к базе данных, то в MySQLi за это отвечают функции mysqli_connect_errno и mysqli_connect_error.

Синтаксис этих функций выглядит вот так:

mysqli_connect_errno();
mysqli_connect_error();

Эти функции не принимают параметров вообще.  Функция mysqli_connect_errno – показывает код ошибки. А функция mysqli_connect_error – показывают информацию об ошибке.

Вот небольшой пример как пользоваться этими функциями:

$load=mysqli_connect("localhost","username","pass","dbname", 3306);
if(!$load){
echo' Ошибка подключения к БД: '.mysqli_connect_error().' Код ошибки:'.mysqli_connect_errno();
exit;
}
$sql=mysqli_query("SELECT username FROM accaunt WHERE id='1'");
if(!$sql){
echo'Ошибка запроса: '.mysqli_error($load).' Код ошибки: '.mysqli_errno($load);
exit;
}
$result=mysqli_fetch_array($sql);
echo $result['username'];

Вот и все, что нужно знать о выводе ошибок. Ничего тут сложного даже и нет. Я всегда пользуюсь этими функциями при разработке проектов, так как это очень удобно. Сразу понимаешь, что и где случилось. На сегодня все. ;)

Постовой

При ранжировании сайтов, поисковая система Google учитывает один фактор доступности сайта. Скорость отклика сайта зависит от расположения ДНС сервера и хостинг сайта. Можно смело заявить, что платное размещение сайтов, является неотъемлемой частью поисковой оптимизации.

php

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

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: %s\n"$mysqli->connect_error);
    exit();
}

if (!

$mysqli->query("SET a=1")) {
    
printf("Errormessage: %s\n"$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: %s\n"mysqli_connect_error());
    exit();
}

if (!

mysqli_query($link"SET a=1")) {
    
printf("Errormessage: %s\n"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

Понравилась статья? Поделить с друзьями:
  • Mysql вывести ошибку запроса
  • N plt ошибка на весах
  • Mzc 303e ошибка e00
  • Mystery game epic games ошибка
  • Mysqli errno коды ошибок