Asked  7 Months ago    Answers:  5   Viewed   60 times

I'm using PHP and mysqli prepared statements. Is there a compelling reason to manually check for errors when executing mysqli_stmt_prepare()? To be more specific I am not asking about the final result just the prepare statement line.

$sql = "SELECT * FROM `users`;";
$stmt = mysqli_stmt_init($db);
mysqli_stmt_prepare($stmt, $sql); // How should I check for error in here
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

PHP manual puts this and only this line in an if statement.

$sql = "SELECT * FROM `users`;";
$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, 'SELECT * FROM `users`;')) {
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
}

I would like to know how to properly check for errors when using prepared statements in mysqli. Is there a good reason to manually check the return value of that function as it is shown in the manual?

 Answers

43

Is there a good reason to manually check the return value of that function as it is shown in the manual?

Nope, there isn't.

Mysqli can check for errors automatically, you just have to ask it to do so.
Configure mysqli to throw an exception every time it gets an error, and you won't have to check any mysqli function for the error manually anymore!

Hence, add the following line before mysqli_connect()

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

and that's all!

Note that you have to deal with possible errors the right way. You can read about it in my article, PHP error reporting

Tuesday, June 1, 2021
 
ajaybc
answered 7 Months ago
82

Never display connection errors manually!

MySQLi will generate a warning if it is unable to open the connection to MySQL. This warning tells you all you need to know including the error code, error message, and the place in the code where it happened. Checking for the error manually will not give you any more information.

If you can't see the warning and your connection cannot be created, it might mean that your PHP is not configured to show them. In that case, you must check the error log file on your server. If you do not know where that is, use phpinfo() to get that information and search for error_log. It will tell you where the error log file is located.

If there is no warning in the error logs, it could mean that your PHP has error reporting silenced (either completely or just warnings). Check your PHP configuration.
In the production environment these settings should be maintained:

  • error_reporting must be E_ALL
  • log_errors must be On
  • display_errors must be Off

In the development environment these settings should be maintained:

  • error_reporting must be E_ALL
  • log_errors must be On
  • display_errors must be On

As you can see in the error message your database username and password has been revealed to the end-user. These are sensitive information which you do not want to show anyone. In fact, a normal user would not understand this cryptic message. This is why display_errors must always be switched off in the production environment. Logging the errors on the server is safe.

Warnings vs. Exceptions

Warnings do not stop the script. If a warning is emitted the script will keep on executing until it encounters a fatal error. In most cases, you would want to throw an exception to stop the script. Do not use die/exit! If mysqli connection cannot be made, an exception should be thrown and if it is unhandled it will bubble up and stop the script with a fatal error. You can configure mysqli to throw exceptions automatically. This is invaluable because all mysqli functions can fail for many reasons and they will not inform you about any problems unless you check for errors manually every single one of them. Use the following line before opening connection:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

Do not catch the exceptions unless you really know what to do with them! One possible use case is described in How to connect properly using mysqli

Can mysqli_error() show any connection-related problems?

No. mysqli_error($conn) expects that the mysqli connection was successful. $conn must be a valid mysqli connection otherwise you would get this error message:

Warning: mysqli_error(): Couldn't fetch mysqli in C:...

Neither $conn->error nor mysqli_error($conn) can display any connection related errors!


Related: Should I manually check for errors when calling “mysqli_stmt_prepare”?

Tuesday, June 1, 2021
 
osondoar
answered 7 Months ago
39

yo need create the user "pma" in mysql or change this lines(user and password for mysql):

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma'; 
$cfg['Servers'][$i]['controlpass'] = '';

Linux: /etc/phpmyadmin/config.inc.php

Tuesday, July 13, 2021
 
ShadowZzz
answered 5 Months ago
86

There is an advantage to using std::for_each instead of an old school for loop (or even the newfangled C++0x range-for loop): you can look at the first word of the statement and you know exactly what the statement does.

When you see the for_each, you know that the operation in the lambda is performed exactly once for each element in the range (assuming no exceptions are thrown). It isn't possible to break out of the loop early before every element has been processed and it isn't possible to skip elements or evaluate the body of the loop for one element multiple times.

With the for loop, you have to read the entire body of the loop to know what it does. It may have continue, break, or return statements in it that alter the control flow. It may have statements that modify the iterator or index variable(s). There is no way to know without examining the entire loop.

Herb Sutter discussed the advantages of using algorithms and lambda expressions in a recent presentation to the Northwest C++ Users Group.

Note that you can actually use the std::copy algorithm here if you'd prefer:

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "n"));
Wednesday, July 28, 2021
 
dzm
answered 5 Months ago
dzm
36

This is how your code should look (with added SQL Injection protection):

<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = mysqli_real_escape_string($_GET['name']);
$text = mysqli_real_escape_string($_GET['text']);

$sqlqr = "INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ('" . $name . "', '" . $text . "', CURRENT_TIMESTAMP);";

mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>

Take a look at what I've done. Firstly I've escaped the user input you're retrieving into the $name and $text variables (this is pretty much a must for security reasons) and as others have suggested you should preferably be using prepared statements.

The problem is that you weren't surrounding string values with single quotes ('), which is a requirement of the SQL syntax.

I hope this helps to answer your question.

Thursday, September 2, 2021
 
Pachvarsh
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share