PHP necessity to check for DB connection errors - php

Since I am trying to provide well formatted code as much as possible, I came up to this question.
In general I check for a database connection error for every prepared statement I create like:
if ($stmt = $mysqli->prepare("...random SQL code here...") {
//bind_param, executes, store_results, etc. here
} else {$err = "Database error";}
But I never check for a database errors on executes. Should I do it?
Does it hurt the performance on big projects more as it would solve a better debugging with more chance on throwing out an useful error code? Or should I forget about those checks at all and just rely on mysql/php/apache logs?
Thanks for helping me out.

Yes, you should test validity of your connection and no it will not affect the performance of your script. The php documentation on those connection commands nearly allways show yoou how.
See there
http://php.net/manual/en/mysqli.construct.php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
.$mysqli->connect_error);
}

Related

How to detect MySQLi initialization error

In my website I am initializing DB connection using values read from config file, like this:
$this->mysqli = new mysqli($databaseInfo->MySQL_Host, $databaseInfo->MySQL_User, $databaseInfo->MySQL_Pass, $databaseInfo->MySQL_Db);
(for the record, values are being read from file properly and when everything is OK, db connection works just fine)
then I ask whether an error occurred during creating MySQLi object:
if (($this->mysqli!=null)&&($this->mysqli->errno == 0)) {
if no, then I want to set an error variable and handle it later in the code...I want this check only passes when no problem occurred...I thought "errno" variable provides sufficient check...
but apparently not, because regardless any error, I produce in config file, the code still jumps into "everything is fine" branch...obviously PHP produce a lot of warnings and finally it crashes on some fatal error related to the fact database doesn't work as expected
so my question is - how to set up this DB connection initial check properly to avoid such situation?
From PHP Manual, try this:
if (!$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}
If using PHP OOP
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
If using procedural style PHP
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>

PHP - Error handling while querying mysql

I am new to web development, so probably there is something I am doing it wrong.
I am using webmatrix for development and playing around with StarterSite sample that webmatrix provides.
In one of the php file (header.php) there is a query to mysql using mysqli extension. I have changed the tablename to some non existent table to simulate error condition. The problem is, after below statement -
$statement->execute();
the script stops.
I inserted a echo statement after execute and that echo string is not displaying on webpage. However when I correct the table name, the echo string after execute is displayed on webpage. So I think the script stops executing after execute when the table name is wrong. I have two questions. How do I stop script from stop executing like this? Secondly How to know for sure that script has stopped executing at some particular statement?
For second part of question, I checked the log file and tracelog file in IISExpress folder. There is no mention of any error, probably because error happened in MYSQL. However, in my MYSQL folder there is no log file, so not sure how to check mysql log.
If I have missed anything, please let me know.
Regards,
Tushar
You should read about mysqli error handling.
Basic error handling example OOP:
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Procedural:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
It depends on what you're logging. In the error log you can define what's being logged. I think you can control the strict mode of the error in the php.ini which will automatically throw error into the access_log or error_log or apache log file.
The trick is to use $mysqli->error in every step of the mysqli querying and db connects to ensure you're getting proper error messages in detail whether to debug, improve the code or to do it correctly.
Here is an example of using $mysqli->error in querying the database.
$result = $mysqli->query($query);
if (!$result and $mysqliDebug) {
// the query failed and debugging is enabled
echo "<p>There was an error in query: $query</p>";
echo $mysqli->error; //additional error
}
You can also use a method where you define mysql error to be true in db conn
// define a variable to switch on/off error messages
$mysqliDebug = true;
// connect to your database
// if you use a single database, passing it will simplify your queries
$mysqli = #new mysqli('localhost', 'myuser', 'mypassword', 'mydatabase');
// mysqli->connect_errno will return zero if successful
if ($mysqli->connect_errno) {
echo '<p>There was an error connecting to the database!</p>';
if ($mysqliDebug) {
// mysqli->connect_error returns the latest error message,
// hopefully clarifying the problem
// NOTE: supported as of PHP 5.2.9
echo $mysqli->connect_error;
}
// since there is no database connection your queries will fail,
// quit processing
die();
}
#ref: https://www.daniweb.com/web-development/php/code/434480/using-phpmysqli-with-error-checking

Script isn't sending login information correctly

I'v just began coding my own script about an hour ago and I'v come across an error that I'm unsure how to fix, It appears that everything is parsing correctly except the username, for some reason when I execute my PHP table create script it's not parsing the username from config.php instead it's executing the script with no username.
I'v put the code though phpcodechecker.com/ and it's given me nothing, not even any warnings, it has me really quite confused, the code looks fine to me but I am quite novice at this so I'v probably missed something HUGE, any help would be greatly appreciated.
Why isn't this code parsing the username through to createtable.php when it attempts to connect??
Code snippets in question;
The way stack formats code blocks confuses the hell out of me so I'll just use pastebin
config.php
createtable.php
This is because you are mixing mysqli and mysql api in config.php which end up with no connection at all
mysqli_connect($db_hostname, $db_username, $db_password)
mysql_select_db($db_database)
To extabilish a correct connectio to database with mysqli (wich is obviously better to use since mysql_* functions are deprecated) do something like this:
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
You can check documentation here
I would like to add that you can use connection from config.php in any other scripts simply requiring it.
require('config.php');
so your creatables.php will look like this
require("config.php");
$sql="CREATE TABLE quoter (
id int NOT NULL AUTO_INCREMENT,
quote text NOT NULL,
quoteby CHAR(50) NOT NULL,
PIMARY KEY (id)
)";
if (mysqli_query($mysqli,$sql))
{
echo "Table 'quoter' was created sucessfully";
}
else
{
echo "Error creating table 'quoter': ".mysqli_error($mysqli);
}
and your config.php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
I would like you to note that $mysqli is the parameter wich handle connection so you need to pass this one while executing operations in your database, eg
mysqli_query($mysqli,$sql);
//^here it is

Mysql_error() Not Catching INSERT Error in PHP

new here and really green to programming, so go easy..
I discovered I have an INSERT that is failing because of a duplicate record error. I figured it out by running the query in a MySQL console with literals, where err#1062 popped up.
What I want to understand is why mysql_error() or mysql_errno() didn't catch this error in my PHP script.
Below is a generic setup of what I've done. I have a form that submits to a php file that calls data_insert()
function data_insert($var1, $var2, $var3, $var4){
$db = db_connect();
$query = "INSERT INTO exampletable (id, id_2, id_3, id_4)
VALUES ('$var1', '$var2', '$var3', '$var4')";
$result = $db->query($query);
if (!$result)
{
echo ('Database Error:' . mysql_error());
}
else
{
echo "Data added to db";
}
}
The DB connection:
function db_connect()
{
$result = new MySQLi('localhost', 'root', 'root', 'dbname');
if (!$result)
throw new Exception('Could not connect to database server');
else
return $result;
}
Result I'm getting is:
Database Error:
PHP echos "Database Error:" because the INSERT fails, but no subsequent MySQL error info is echoed. Honestly, I'm not exactly sure what I'm supposed to see, but through reading some other SO questions, I've double-checked my php.ini file for error handling and E_ALL and display_errors is set appropriately (although not sure if it matters in this case).
Is there something in my logic that I'm not understanding, like the scope of the link resource mysql_error() takes?
Thanks for your help, I'm hoping this is something embarrassingly obvious.
I know the above is missing XSS and security precautions and uniform exception handling. Baby steps though. It's simplified here for discussion's sake.
You're using mysqli (note the i) for your DB operations, but are calling mysql_error (no i). They're two completely different interfaces, and do not share internal states at at all. DB handles/results from one are not usable in the other.
Try mysqli_error() instead (note the I).
As far as I can tell, you appear to be using the MySQLi class for connecting and queries, but you're trying to access MySQL error message. MySQLi and MySQL aren't the same, so errors in one will not show in the other. You should look up error handling for MySQLi, not MySQL.
You are confusing two seperate methods for connecting to a mySQL DB.
mysql_error() will only work on queries that are run through mysql_query().
As you are using mysqli, you must use mysqli_error()

Check if MySQL server is able to accept connections

What is the best way to check, from PHP, if connection to a MySQL server will succeed? I've seen some solutions that first try to open a socket connection (with fsockopen) and connect to MySQL (via whatever extension you are using) only if the socket connection was successful. I'm not too sure about this since you have to make two connections every time, does that hammer the server too much?
My problem is that if my MySQL server locks-up or stops working for whatever reason the web page just stops working (it load for a long time and then usually comes back with a 504 gateway time-out error). I'd like to display a user friendly error message if MySQL is not available. This would also, hopefully, avoid MySQL being hammered even more if it is already struggling, as new clients won't connect to it until the server comes back up.
I'm using MySQLi extension if that is relevant.
What your need is the MYSQLI_OPT_CONNECT_TIMEOUT specify in mysqli::options
details
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>
From http://www.php.net/manual/en/mysqli.connect.php

Categories