mysql_connect doesn't work second time - php

duplicate of unanswered: How to reconnect in php adodb after exceptions: Mysql server gone away or Lost connection to MySQL server during query
mysql_connect works the first time, but never works after that...
$connectDb = mysql_connect(secret, secret, secret);
mysql_select_db("secret", $connectDb);
$sleepPeriod = 1800;
sleep($sleepPeriod);
while (true) {
$result = mysql_query("good query", $connectDb);
if (!$result) {
if (mysql_error()=='MySQL server has gone away') {
echo "MySql connection was disconnected... reconecting...\n";
$connectDb = mysql_connect(secret, secret, secret);
mysql_select_db("secret", $connectDb);
continue;
} else {
die("Invalid Query: ".__FILE__.':'.__LINE__.' '.mysql_error()."\n");
}
}
//DO STUFF
sleep($sleepPeriod);
}
if a timeout or disconnect happens mysql_connect seems to fail and mysql_error continually returns "MySQL server has gone away", which results in an infinite loop that can go for days. is there some other way to clear the error response of mysql_error or to make mysql_connect run a second time without having to restart this program manually or resorting to cron.
I just noticed that mysql_connect has a strange(stupid?) parameter called new_link, however it would be an outrageous design if php's mysql code purposefully disables reconnects on timeout by default... I'll test regardless and get back.

mysql_connect doesn't care if the connection has disconnected or timed-out it will never connect a second time unless you call it with the parameter new_link with the value true.
mysql_connect($server,$username,$password,true);

Related

How do I force reconnecting to my database in php?

I wanted my web system to automatically reconnect to the database if it reaches to maximum user connection. Or is there anyway i could reload the page automatically till it is connected to the database
$conn = new mysqli(DB_HOST,DB_USER,DB_PSWD,DB_NAME);
if($conn->connect_error)
die("Failed to connect database ".$conn->connect_error );
You can setting the retry variable($retry) as a flag to mark the DB connection status with default value you want. While connect DB , if it's ok then update retry flag = 0($retry=0) , else reduce the retry one unit ($retry--). Also you don't die process when have error exception.
You can enclose the connection in a function and call it many times you want to retry the connection:
function connectDB(DB_HOST,DB_USER,DB_PSWD,DB_NAME)
{
return $conn = new mysqli(DB_HOST,DB_USER,DB_PSWD,DB_NAME);
}
if(connectDB()->connect_error)
{
sleep(1);
if(connectDB()->connect_error)
{
die("Failed to connect database ".$conn->connect_error );
}
}
With sleep(1) you delay the script to retry the connection after 1 second.
Anyway, you should find the cause of the connection error and solve it; this solution may help you in the case the server is sometimes slow to respond.

Is there a way to ping MSSQL database before connecting to it

The connection to the database is very fragile, so I try to test the connection before make a link to it. I found pg_connect and mysql_ping and how-do-i-ping-the-mysql-db-and-reconnect-using-pdo, but none has anything to do with MSSQL or function that I can use.
Is there a way I can test the database before I connect to it?
You might set the timeout to a very small number and call something like
SELECT 1;
or
SELECT GETDATE();
and see, if there is some result coming back...
If the connection is broken, such tiny requests should break as well.
In case fragile does not mean broken, you might measure a standard call and compare the execution speed...
You could try to ping the server + corresponding port to see if server accepts connections.
$host = '127.0.0.1'; // ip address, could be localhost
$port = 1433; // your mssql port
$timeout = 1; //time to wait in seconds for response
if($fp = fsockopen($host,$port,$errCode,$errStr,$timeout))
{
// Server is OK - responding
} else {
// Server not respoded on given port in given time limit
}
fclose($fp);

Best approach to see if a MySQL Server is up and running

I have a Master - Slave setup for a web application written in PHP. I have a pool of slaves I use for reading, and a Master that is used for writes (and reads if a write has been sent this request). I would like to incorporate an automated system for removed crashed servers from the read pool. Currently I am using:
foreach($readers as $reader)
{
$fp = #fsockopen($reader['host'],3306,$errno,$errstr,1);
if(!$fp)
{
//Remove from pool
}
unset($fp);
}
My primary question is there a more reliable method. I have had quite a few false positives, and vice versa because it is not actually checking for a MySQL server, but rather just a connection on port 3306. Is there a way to check for a MySQL server without raising an exception, which is the behaviour of the PDO and MySQLi extensions in PHP.
You could just use mysql_connect() and check the result for false, and close the connection right away on success. You can make a dummy account with no privileges for that if you like.
That's really the only reliable way, especially if you want to distinguish a running MySQL server from any other random process listening on port 3306.
You could use mysql_ping() to check if a current DB Connection you have open is still alive
Here is the example posted at http://www.php.net/manual/en/function.mysql-ping.php
<?php
set_time_limit(0);
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db = mysql_select_db('mydb');
/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}
/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysql_free_result($result);
/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>
The best way to check if any service is alive is to actually use it. So for MySQL try to connect and execute some fast query, for web server try to fetch some file, for PHP try to fetch some simple script...
For MySQL master/slave setup, one of the solutions is to actually check the state of replication. You can check how many transactions is the slave behind master and decide to stop using that slave when/while it has old data. (I don't do the replication myself, but I think you need to compare the variables Read_Master_Log_Pos and Relay_Log_Pos)

mysqli never returns anything

As part of a PHP web application, I'm querying a MySQL database using mysqli and prepared statements.
I've used exactly the same code on a few queries and it works, but on one particular query, it always returns an empty record set. I've run exactly the same query from the MySQL command line, and it correctly returns the result. I've checked the parameters being passed in, and they're fine.
I've spent the best part of a day trying to figure out why I'm always getting an empty record set with no errors or warnings. I've got PHP's errors set to display on the page, and I've got them set to E_ALL|E_STRICT. I still don't get any warnings or errors.
I've tried all the obvious things, like making sure I can actually connect to the database, checking the parameters that are being passed in, and making sure the row I'm trying to return actually exists in the database. I've had var_dump()s and die()s all over the page to check what's coming back, and it's always a legitimate, but empty, recordset.
function salt() {
return("I've removed my salt from this sample code");
}
function openDatabase() {
$conn = new mysqli("127.0.0.1", "username", "password", "database")
or die("Error: Could not connect to database.");
return($conn);
}
function checkUserCredentials($username, $password) {
$goodPassword = md5(salt().$username.$password);
$conn = openDatabase();
$query = $conn->stmt_init();
$query->prepare("SELECT id FROM users WHERE email = ? AND passwordHash = ?")
or die('Problem with query');
$query->bind_param("ss", $username, $goodPassword)
or die('Error binding parameters');
$query->execute() or die("Could not execute");
$query->bind_result($col1) or die ("Could not bind result");
if ($col1 !== 0) {
die("Authentication Complete");
} else {
die("Authentication Failure! Number of Rows: ".$query->num_rows." Username: " . $username . " Password Hash: " . $goodPassword);
}
}
Any feedback is appreciated. I'm sure I'm missing something simple, but if I didn't shave my head I'd be tearing my hair out right now.
Thanks
I'm not familiar with the mysqli library (I usually use PDO which provides a very similar cross platform API) so I can't immediately see any problem. However, you might try watching the mysqld log. See here for info:
http://dev.mysql.com/doc/refman/5.1/en/query-log.html
By tailing the log, you should be able to see the exact query that was submitted.
One final note, I notice you're using a fixed salt value. Wouldn't it be better to generate this value randomly each time you need it and then store it in the users table? Generally, a salt is not intended to be secret, it's just there to prevent people precomputing tables of passwords using the hash algorithm that you use.
In case anyone else runs into similar issues, it really helps if you run fetch() on your mysqli_stmt object.
In my code above, the solution looks like this:
$query->bind_result($col1) or die ("Could not bind result");
$query->fetch(); // <--- How could I forget to do this?
if ($col1 !== 0) {
return true;
} else {
return false;
}
Added on behalf of OP

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