How to detect MySQLi initialization error - php

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

Related

PHP mysqli acting really screwy

I am attempting to use PHP to connect to a database for the first time. I found an online tutorial that was teaching me how to use mysqli to do this. It talked about mysqli_connect($host, $name, $pass, $db) and that worked just fine. The problem was when the tutorial asked me to check for errors using the function mysqli_connect_errno() because apparently whatever version of PHP I am running doesn't recognize that function. But according to the internets, im the only weirdo who's copy of PHP is having this issue. Why can't my PHP recgonize mysqli_connect_errno()? (Note: I am running wampserver on a Windows 8.1 desktop and PHP version is 5.5.12) (UPDATE: the actual username is supossed to be "web")
Here is my PHP Code:
<?php
$sql = mysqli_connect("localhost", "sweb", "nsjk99", "Inventory");
if( mysqli_connect_errno() ) {
die("Database connection failed: " . mysqli_connect_error() . "( " . mysqli_connect_errorno() . ")");
} else {
echo "<p>Your connection was a success</p>";
}
?>
Result:
The function is called mysqli_connect_errno() and not mysqli_connect_errorno(), as you have on line 4.
Edit
You don't need to pass the connection link as a parameter as stated in the manual.
The function catches the error number from the last call to mysqli_connect().
Thanks to David Rosa for the warning.

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

PHP necessity to check for DB connection errors

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

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

Testing php / mysqli connection

I am looking for a way to test just the connection portion of a php / mysqli connection. I am migrating from a LAMP server build on Vista to the same on Ubuntu and am having fits getting mysqli to work. I know that all of the proper modules are installed, and PhpMyAdmin works flawlessly. I have migrated a site over and none of the mysqli connections are working. The error that I am getting is the "call to member function xxx() on non-object" that usually pops up when either the query itself is bad or the query is prepared from a bad connection. I know that the query itself is good because it works fine on the other server with the exact same database structure and data. That leaves me with the connection. I tried to write a very simple test connection and put it in a loop such as ..
if(***connection here ***) {
echo "connected";
}
else {
echo "not connected";
}
It echoes "connected", which is great. But just to check I changed the password in the connection so that I knew it would not be able to connect and it still echoed "connected". So, the if / else test is clearly not the way to go....
mysqli_connect() always returns a MySQLi object. To check for connection errors, use:
$mysqli_connection = new MySQLi('localhost', 'user', 'pass', 'db');
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
echo "Connected.";
}
For test php connection in you terminal execute:
$ php -r 'var_dump(mysqli_connect("localhost:/tmp/mysql.sock", "MYSQL_USER", "MYSQL_PASS",
"DBNAME));'
You need more error handling on the various database calls, then. Quick/dirty method is to simply do
$whatever = mysqli_somefunction(...) or die("MySQL error: ". mysqli_error());
All of the functions return boolean FALSE if an error occured, or an appropriate mysqli object with the results. Without the error checking, you'd be doing:
$result = $mysqli->query("blah blah will cause a syntax error");
$data = $result->fetchRow(); // $result is "FALSE", not a mysqli_object, hence the "call to member on non-object"

Categories