Php new mysqli error

mysqli_connect_error

Returns the error message from the last connection attempt.

Parameters

This function has no parameters.

Return Values

A string that describes the error. null is returned if no error occurred.

Examples

Example #1 $mysqli->connect_error example

mysqli_report ( MYSQLI_REPORT_OFF );
/* @ is used to suppress warnings */
$mysqli = @new mysqli ( ‘localhost’ , ‘fake_user’ , ‘wrong_password’ , ‘does_not_exist’ );
if ( $mysqli -> connect_error ) /* Use your preferred error logging method here */
error_log ( ‘Connection error: ‘ . $mysqli -> connect_error );
>

mysqli_report ( MYSQLI_REPORT_OFF );
/* @ is used to suppress warnings */
$link = @ mysqli_connect ( ‘localhost’ , ‘fake_user’ , ‘wrong_password’ , ‘does_not_exist’ );
if (! $link ) /* Use your preferred error logging method here */
error_log ( ‘Connection error: ‘ . mysqli_connect_error ());
>

See Also

  • mysqli_connect() — Alias of mysqli::__construct
  • mysqli_connect_errno() — Returns the error code from last connect call
  • mysqli_errno() — Returns the error code for the most recent function call
  • mysqli_error() — Returns a string description of the last error
  • mysqli_sqlstate() — Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

Источник

mysqli_error

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

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

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

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

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

Примеры

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

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

$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 операции

User Contributed Notes 7 notes

The mysqli_sql_exception class is not available to PHP 5.05

Читайте также:  Javascript in pdf tutorial

I used this code to catch errors
$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:
$query = «SELECT XXname FROM customer_table » ;
$res = $mysqli -> query ( $query );

if (! $mysqli -> error ) printf ( «Errormessage: %s\n» , $mysqli -> error );
>

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

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
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:\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.

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

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.

Читайте также:  Python string get last character

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

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

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

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

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

Читайте также:  Html academy великий дешифровщик

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

Источник

PHP mysqli: error() Function

The mysqli_error() function / mysqli::$error returns the last error description for the most recent function call, if any.

Object oriented style

Procedural style

string mysqli_error ( mysqli $link )
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

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:

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(); ?> 
Errormessage: Unknown system variable 'a'

Example of procedural style:

 if (!mysqli_query($link, "SET a=1")) < printf("Errormessage: %s\n", mysqli_error($link)); >/* close connection */ mysqli_close($link); ?> 
Errormessage: Unknown system variable 'a'
 // 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); ?> 

Previous: error_list
Next: field_count

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

stdClass is PHP’s generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out).

It is useful for anonymous objects, dynamic properties, etc.

An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array. Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.

'; $stdInstance = json_decode($json); echo $stdInstance->foo . PHP_EOL; //"bar" echo $stdInstance->number . PHP_EOL; //42 //Example with associative array $array = json_decode($json, true); echo $array['foo'] . PHP_EOL; //"bar" echo $array['number'] . PHP_EOL; //42
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью