Check if MySQL server is able to accept connections - php

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

Related

Can't connect to database with php? [duplicate]

This question already has answers here:
How to make mysqli connect function?
(2 answers)
Closed 5 years ago.
I'm trying to connect to my database via php but I keep getting a 500 Internal Server Error. It is hosted on GoDaddy. I'm fairly new to php. Here is my code:
<?php
// Create connection
$conn = mysql_connect('server name', 'username', 'password');
mysql_select_db('users', $conn);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>
Obviously I have entered my server name, username and password but not showing them here. I can't get it to connect at all. I wanted to be able to just to display a row of data on a page to check it works but I can't even get that far yet! I'm probably missing something obvious. Any help would be great. Thanks!
There are several reasons for getting 500 error on page and will discuss all of them below.
You have used mysql_* function to establish connection to database which is deprecated in newer version of php.
You may have issue with .htaccess code which is blocking you.
However you can check some points to figure out your issue.
Check your .htaccess file whether it is blocking you or not
Check your php version (If you php version is >= 5.5) then try below.
<?php
// Create connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
Hope this will help you!!
Thanks & Regards
you seems to be use the mysql as an object and it is not supported only mysqli that can behave like this .
so if you need to use mysql extension and it is not recommend since it is deprecated.
<?php
// Create connection
$conn = mysql_connect('server name', 'username', 'password');
mysql_select_db('users', $conn);
// Check connection
if (!$conn) {
die("Connection failed: " . mysql_error());
} else {
echo "Connected successfully";
}
?>

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.

Can't connect to database "Fatal error: Call to undefind function mysqli_connect()"

I've been scouring this site for 5 hours now trying to get this sorted, I rarely ask for help but this is one of the weirdest and most annoying things I've encountered.
First of all I'd like to say that this DID work fine, I have limited examples of what the cause is but I'll list them anyway.
Here's the full error message:
Fatal error: Call to undefind function mysqli_connect() in C:\wamp\www\game\connect.php on line 3
And here's the code
<?php
// Create connection
$con=mysqli_connect("localhost","root","","game");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'game');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
Weird thing is, it was working completely fine and just suddenly stopped, this has happened more than once.
Here's what I've tried:
Checking the extensions are enabled -
Rebooting various times -
Setting the correct php path -
Using many example codes that "work" -
I also had some code that inputted data straight from phpdesigner into the database, which successfully worked, but that no longer works and I've made literally 0 changes.
The last time it stopped working, I filled out a registration form on my site as a test (that doesn't work either) and it suddenly went off. When filling in the form I click register and nothing happens besides a refresh.
Bit extra: In my httpd file the pfp and pfpinidir are as follows
php5_module"c:/wamp/bin/php/php5.5.12/php5apache2_4.dll"
PHPIniDir "C:\wamp\bin\apache\apache2.4.9\bin\php.ini"
Your mysqli extension might not be enabled. so u need to enable that.
You have two PHP binaries on your machine. One is connected to the Apache, and is the one u use when you surf to a web page.
The phpinfo() shows you which php.ini file is used by the web php binary. u need to edit this file and in it activate the mysqli extension
You're trying to connect to DB twice, plus you're mixing MySQL APIs with mysql_error(), they do not mix together.
The 4th parameter is the DB name which is what you've done in the first example.
Use either:
<?php
// Create connection
$con=mysqli_connect("localhost","root","","game");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
or omit ,"game" from mysqli_connect() - while mysqli_error() requires DB connection parameter.
<?php
// Create connection
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'game');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($con));
}
?>

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 1045 Access Denied

Good Morning,
I wrote the code block below on my local Windows 7 PC and tried to run it. Unfortunately, I received:
Connect Error (1045) Access denied for user 'dbuser'#'myhost(using password: YES)
I have granted dbuser Insert, Select, Update, and Execute using both localhost and % for this database schema. I am able to mysql -u dbuser -p from command line on server as well.
Here's the code block:
<?php
/* Set Variables */
$host="serveripaddress";
$db="dbname";
$username="dbuser";
$pass="pass";
/* Attempt to connect */
$mysqli=new mysqli($host,$username,$pass,$db);
if (mysqli_connect_error()){
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
}
?>
I'm having difficulty understanding whether the above code block is causing my error, or whether there's something required to be done on the server. Can anyone suggest some areas of investigation?
Thanks,
Sid
Make sure that if you're using a hostname for the GRANT in MySQL, that MySQL can properly resolve that hostname to the IP you're connecting from.
For instance, if you do
GRANT blah ON *.* to user#somehost
you have to remember that MySQL won't see 'somehost', it'll see an IP address. It'll have to do a reverse lookup to get a hostname, and if the IP either doesn't have a reverse mapping, or maps to something completely different, MySQL won't give access.
Unless you can guarantee that the reverse mapping is stable, it's best to use IP addresses for remote access accounts in MySQL.
<?php
/* Set Variables */
$host="127.0.0.1:3306";
$db="dbname";
$username="dbuser";
$pass="pass";
/* Attempt to connect */
$mysqli=new mysqli($host,$username,$pass,$db);
if (mysqli_connect_error()){
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
else
{
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
}
?>
First of all, add these braces in for your if/else statement. Second, try hardcoding the IP. I just ran this with an IP set to a variable (didnt work) and then I hardcoded it, worked just fine.

Categories