Php как узнать ошибку sql

(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

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


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.


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

?>


l dot poot at twing dot nl

16 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'] . "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 );
  }
?>


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

18 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?


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


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


scott at rocketpack dot net

19 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


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$queryn<br>";
        return $result;
    }


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

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


Gerrit

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


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

Warning mysqli_error() expects parameter 1 to be mysqli, null given inВводная: есть PHP файл который регистрирует пользователей в базе данных. Вроде бы все хорошо, но пользователь не записывается в базу.

Перед записью открывается соединение, выполняются проверки. То есть соединение с базой данных есть. Сам SQL-запрос составлен правильно, все хорошо. Но данные не записываются в базу, хоть ты тресни.

Возникают два вопроса:

  1. Почему не работает.
  2. Как понять, почему не работает.

Второй вопрос более приоритетный, и что?

Для того, что бы посмотреть ошибки, нужно после запроса:

$result = $con->query("INSERT INTO ... запрос ...");

Добавить код, в итоге получиться:

$result = $con->query("INSERT INTO ... запрос ...");
if (!$result) {
var_dump(mysqli_error($result));
}

При этом мы получим ошибку PHP. Это важно понимать, тут ключевая фраза ошибка PHP.
Я получал следующие ошибки:

  • Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /var/www/fastuser/data/www/webinsert.ru/reg.php on line 133.
  • Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in /var/www/fastuser/data/www/webinsert.ru/reg.php on line 133

Пользователи на просторах интернета пишут всякий бред, из разряда ты что, не умеешь читать ошибки что ли? Да, от души братуха, о чем говорят ошибки:

MySQL ожидает параметр 1, а получает NULL  или логику. То есть ничего не понятно.

Warning mysqli_error() expects parameter 1 to be mysqli, null given in

Нам нужно понять, в чем ошибка SQL. Я пробовал выполнить запрос на сервере, но он срабатывал.

Что бы понять в чем ошибка SQL нужно перед соединением с БД прописать код:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

И, о чудо, после ввода данных в форму регистрации появилась ошибка MySQL:

data too long for column email at row 1

И теперь стало все понятно.

Данные слишком длинные для столбца ’email’ почты в строке 1.

Смотрю в базу и вижу.

varchar 20

А количество символов в поле e-mail которое я вводил было 22. Вот в чем моя ошибка.


Анатолий Бузов

Анатолий Бузов / об авторе

Обучаю HTML, CSS, PHP. Создаю и продвигаю сайты, скрипты и программы. Занимаюсь информационной безопасностью. Рассмотрю различные виды сотрудничества.


mysql_error

(PHP 4, PHP 5)

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

Описание

string mysql_error
([ resource $link_identifier = NULL
] )

Возвращает текст ошибки выполнения последней функции MySQL.
Ошибки работы с MySQL больше не вызывают сообщений в PHP. Вместо
этого используйте функцию mysql_error(), для
получения сообщения об ошибке. Учтите, что функция возвращает текст
ошибки только последней выполненной функции MySQL (исключая
mysql_error() и mysql_errno()),
поэтому убедитесь, что вы вызываете данную функцию до вызова
следующей функции MySQL.

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


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

Вернуться к: MySQL

Как найти ошибку в SQL-запросе

SQL-запрос — это то, что либо работает хорошо, либо не работает вообще, частично он никак работать не может, в отличие, например, от того же PHP. Как следствие, найти ошибку в SQL-запросе, просто рассматривая его — трудно, особенно если этот запрос снабжён целой кучей JOIN и UNION. Однако, в этой статье я расскажу о методе поиска ошибок в SQL-запросе.

Поскольку обычно в SQL-запрос подставляются какие-то переменные в PHP, то необходимо его сначала вывести. Сделать это можно, например, так:

<?php
  $a = 5;
  $query = "SELECT FROM `table` WHERE `id` = '$a'";
  $result_set = $mysqli->query($query); // Не работает
  echo $query; // Выводим запрос, который отправляется
?>

В результате, скрипт выведет такой запрос: SELECT FROM `table` WHERE `id` = ‘5’. Теперь чтобы найти ошибку в нём, надо зайти в phpMyAdmin, открыть базу данных, с которой происходит работа, открыть вкладку «SQL» и попытаться выполнить запрос.

И вот здесь уже ошибка будет показана, не в самой понятной форме (иногда прямо точно описывает ошибку), но она будет. Вот что написал phpMyAdmin: «#1064 — 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 ‘FROM `table` WHERE `id` = ‘5’ ORDER BY `table`.`id` ASC LIMIT 0, 30′ at line 1«. Это означает, что ошибка рядом с FROM. Присматриваемся к этому выделенному нами небольшому участку и обнаруживаем, что мы забыли поставить «*«. Исправляем сразу в phpMyAdmin эту ошибку, убеждаемся, что запрос сработал и после этого идём исправлять ошибку уже в коде.

С помощью этого метода я нахожу абсолютно все ошибки в SQL-запросе, которые мне не удаётся обнаружить непосредственно при осмотре в PHP-коде.

Надеюсь, теперь и Вы сможете найти ошибку в любом SQL-запросе.

  • Создано 01.05.2013 10:54:01


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Понравилась статья? Поделить с друзьями:
  • Php вывод ошибок в переменную
  • Php вывод ошибок в консоли
  • Php вывод ошибок в html
  • Php вывести ошибку в файл
  • Php вывести ошибку в div