new mysqli(): how to intercept an 'unable to connect' error? - php

I'm doing this (yes, I'm using wrong connection data, it's to force a connection error )
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
exit (3);
}
But PHP is doing this php_warning:
mysqli::mysqli(): (28000/1045): Access denied for user 'my_user'#'localhost' (using password: YES)
In the example I'm using wrong connection data to force a connection error, but in the real world the database could be down, or the network could be down... etc..
Question: Is there a way, without suppressing warnings, to intercept a problem with the database connection ?

You need to tell mysqli to throw exceptions:
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
echo "message: " . $e->message; // not in live code obviously...
exit;
}
Now you will catch the exception and you can take it from there.

For PHP 5.2.9+
if ($mysqli->connect_error) {
die('Connect Error, '. $mysqli->connect_errno . ': ' . $mysqli->connect_error);
}
You'll want to set the Report Mode to a strict level as well, just as jeroen suggests, but the code above is still useful for specifically detecting a connection error. The combination of those two approaches is what's recommended in the PHP manual.

Check $connection->connect_error value.
See the example here: http://www.php.net/manual/en/mysqli.construct.php

mysqli_report(MYSQLI_REPORT_STRICT);, as described elsewhere, gives me an error and stops the script immediately. But this below seems to provide the desired output for me...
error_reporting(E_ERROR);
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
if($connection->connect_errno)
{
// Database does not exist, you lack permissions, or some other possible error.
if(preg_match($connection->connect_error, "Access denied for user"))
{
print("Access denied, or database does not exist.");
}
else
{
print("Error: " . $connection->connect_error);
}
}
Attempting to catch this error with try..catch() will fail.

Related

multiple mysqli objects overwrite each other

If I create two parallel connections to two servers:
$gw03 = new mysqli('gw03.example', 'user', 'pass', 'db');
$gw04 = new mysqli('gw04.example', 'user', 'pass', 'db');
if (!$gw03->connect_errno) {
...
} else if (!$gw04->connect_errno) {
...
} else {
echo "Failed to connect to gw03: (" . $gw03->connect_errno . ") " . $gw03->connect_error . PHP_EOL;
echo "Failed to connect to gw04: (" . $gw04->connect_errno . ") " . $gw04->connect_error . PHP_EOL;
}
If gw03 is available but gw04 is not, the following is the result
Failed to connect to gw03: (2002) No route to host
Failed to connect to gw04: (2002) No route to host
The failure to connect to $gw04 seems to overwrite $gw03. Aren't $gw03 and $gw04 separate objects? What's going on here?
Unfortunately, mysqli suffers from bad design. The properties connect_errno and connect_error are not really properties. They are just shortcuts to global variables. When the second connection fails the global variable is overwritten internally.
This is a very good reason to stop checking for mysqli errors manually. When an error happens your code should throw an error instead of a warning or failing silently. This error should be properly handled by your application and logged in a secure place on the server. Don't try-catch or echo the error message to the user!
To enable mysqli error reporting you should add the following line before any new mysqli()/mysqli_connect():
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This setting will tell mysqli to throw an exception as soon as an error is encountered. No more manual checking and no more problems with global variables overwriting themselves.
They are separate connections but the connect_errno method "returns the error code from last connect call".
https://www.php.net/manual/en/mysqli.connect-errno.php
You will want to check for a connection error right after each connection attempt.
$gw03 = new mysqli('gw03.example', 'user', 'pass', 'db');
# check $gw03 for connection error before attempting next connection
$gw04 = new mysqli('gw04.example', 'user', 'pass', 'db');

Why is my catch exception code not working?

I can connect the database and the PHP but if I intentionally mess up the database, it doesn't do the code for the catch. The catch is not working. It only displays the warning. I would also like to know how to get rid of that.
This is the warning I get:
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'mytodsssssasdsdasdassdos' in D:\XAMPP\htdocs\projects\index.php on line 10
What am I doing wrong?
Here is my PHP code
<?php
$user = 'root';
$password = '';
$db = 'mytodsssssasdsdasdassdos'; //real DB name is mytodos
try {
$db = new mysqli('localhost', $user, $password, $db);
} catch (mysqli_sql_exception $e) {
die (var_dump('Unable to Connect to the Database.'));
} //echo 'Connected.';
By default error reporting for mysqli is disabled. The only "error" you ever get is the warning when the connection can't be established. You can't catch warnings in PHP with try-catch. However, there is a very simple solution. Enable error reporting properly and you will be able to catch all mysqli errors.
try {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', $user, $password, $db);
} catch (mysqli_sql_exception $e) {
// Do something with the exception here and rethrow it.
throw $e;
}
On the unrelated note, it doesn't look like you need to catch anything there. Just stick to the standard way of connecting without any catching:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', $user, $password, $db);
$db->set_charset('utf8mb4');

Can't Connect to a Database on IPOWER hosting - PHP / MySQL

Please help me connect to a DB - I need to get this to work:
<?php
require_once 'general.php';
try {
$db = new PDO('mysql:host=account.ipowermysql.com;dbname=zipcodes', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
} catch (PDOException $e) {
print 'Oh SNAP ... Error!: ' . $e->getMessage() . '<br/>';
die();
}
If i run it as is, i get a 500 error page.
If I add ?> at the end, I get a blank page.
If I run "DB-connect" code generated by IPOWER it works.
IPOWER generated code:
<?php
$link = mysql_connect('account.ipowermysql.com', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(zipcodes);
?>
I guess the server is configured not to show PHP errors, but a 500 error page instead...
PS - here is general.php code:
<?php
error_reporting(0);
#ob_start();
session_start();
function echo_session($arg) {
if(isset($_SESSION[$arg])) {
return $_SESSION[$arg];
} else {
return '';
}
}
PS2 - original code (at the top) works on GoDaddy and MediaTemple ... it's something with IPOWER ...
I'm a noob and I need this to work, but don't know how to.
Please help

Connection to db using php in localhost

Even if I have used LAMPP many times, this time something goes wrong. When I visit the browser(chrome) nothing echos. Here is my code:
index.php
<?php
error_reporting(E_ALL); /*after edit*/
$link = mysqli_connect('localhost', 'root', 'root', 'db');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>
Do I miss something? The output is nothing. By the way i write my files in
var/www/html/my_pages
and i call it this way: localhost/my_pages. Simple echos are working and php in general is fine. Something goes wrong with my db connection.
Use this code
<?php
$link = mysqli_connect('localhost', 'root', 'root', 'db');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
else
{
echo 'Connected successfully';
}
?>
Yes probably, because mysqli_connect() method return the object, not Boolean value.
You can verify the connection with the following code:
if($link->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
return false;
}
else{
echo "Connection Successful";
return $link;
}
Why not using PDO.
$dsn = "mysql:host=localhost;dbname=db";
try {
$pdo = new PDO($dsn, "root", "");
} catch (PDOException $ex) {
$ex->getMessage();
}
with PDO you can change anytime you need the Db vendor:
http://php.net/manual/en/book.pdo.php
<?php
echo phpinfo();
?>
Run this file and get all PHP and apache details. Search for mysqli support in it. If it is supported, you should have something like below.
Also check for your root directory
Thanks everyone for the response! I found the problem. Something went wrong and mysqli wasn't enabled in php. That's why i had this error Fatal Error:Call to undefined function mysqli_connect() in /var/www/html/diamond/index.php on line 8 I reinstalled php and problem solved :)

Can't Link To MySQL database

I am learning MySQL/PHP and I cannot figure out how to connect to MySQL on my localhost. I have written a short bit of code and I included root as my user name and root as my password because I have not set these elements yet (as far as I know). I feel that perhaps I am missing something in regards to the username/password combination. However, I feel that this should not be an issue because I have not tampered with the default conditions.
I need some help.
My code is below:
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=shirts4max;port=3306", "root", "root");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf-8'");
} catch (Exception $e) {
echo "Could not connect to the database.";var_dump($e);
exit;
}
I am only seeing the error message on my page:
"Could not connect to the database."
Thank for reading. Please help me Obiwan.
Show the real error. Avoid using root except for maintenance.
From the PDO Manual page here, modified for you
<?php
$dsn = 'mysql:dbname=shirts4max;host=localhost';
$user = 'root';
$password = 'root';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Have you tried connecting via command line using: mysql -uroot -proot -hlocalhost -p3306? If you can't connect that way, the PDO connection won't go through either. Playing with the connection info via command line gives you a nice easy way to find what works, then include it in your code. Also, if you've not set the user/pw, it's possible there isn't one currently, so you wouldn't need those parameters at all.

Categories