Condition in the error: 'mysql has gone away' - php

I have a server and it performs actions every 10 seconds, but sometimes, it returns the error 'mysql has gone away'.
I wonder when this error is returned for the page to be refreshed.
I tried the following way but it did not work:
$remote_db = mysql_pconnect($remote_db_host, $remote_db_user, $remote_db_pass) or die (mysql_error());
if(!$remote_db) {
//error on connect
echo '<meta http-equiv="refresh" content="1">';
}
mysql_select_db($remote_db_name, $remote_db) or die (mysql_error());

That's a timeout message. Your PHP code took too long to do anything with the MySQL server and therefore it went away.

The issue is that the persistent connection you are using have died.
So, stop using mysql_pconnect and switch to mysql_connect.
For most cases it is actually speedier to do a normal connect than to try to use a persistant connection.
(And as a side-note: you should really take a look at PDO. mysql_ usage is strongly discouraged.)

Related

Uncalled function throws 'mysqli_stmt object is not fully initialized' uncaught error [duplicate]

If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.

pg_connect is pretty slow in case of error

I have a php script that is used to store some info in a postgresql db. In this script I am using a function to store some logs about certain db operations. During tests I found out that my script will log my errors related to pg_connect function, only after 4-5 seconds - and this represents a big issue for me.
Below you can find my tests and the results:
Case 1 - no error in pg_connect function:
Log("START DBCONN - without errors");
$dbconn = pg_connect("host=$host dbname=$dbname user=$dbuser password=$dbpassword");
if(!$dbconn){
Log("ERROR: Could not connect to database");
}
Log("END");
Case 2 - error in pg_connect:
Log("START DBCONN - with errors");
$dbconn = pg_connect("host=$host12 dbname=$dbname user=$dbuser password=$dbpassword");
if(!$dbconn){
Log("ERROR: Could not connect to database");
}
Log("END");
Results
case 1:
[12-Jan-2016 09:31:21] START DBCONN - without errors
[12-Jan-2016 09:31:21] END
case 2:
[12-Jan-2016 09:31:59] START DBCONN - with errors
[12-Jan-2016 09:32:03] ERROR: Could not connect to database
[12-Jan-2016 09:32:03] END
Do you know a solution for this ? because, I couldn't find one, yet :(
Thanks for your help !
Depending on the nature of the errors, there may be different reasons for it:
If the username or password is wrong, the server may delay the negative response to make brute-forcing a valid combination more cumbersome.
If the host is not reachable, the tcp connect timeout may be several seconds.
Both issues are hard to fix in a clean way.
There are also error conditions which should not result in a delay, for example:
if the host is reachable, but the database server is not running (i.e. "Connection refused").
The time to fail in case of a non-responding remote host can be adjusted with the connect_timeout option in the pg_connect() call.
PHP's pg_connect() documentation does not give any detail on connect_timeout but it just passes it to libpq, the C client library, where it's documented as:
http://www.postgresql.org/docs/current/static/libpq-connect.html
connect_timeout
Maximum wait for connection, in seconds (write as a decimal integer string). Zero or not specified means wait indefinitely. It is
not recommended to use a timeout of less than 2 seconds.
However, the 4 seconds before failure shown in the question seem reasonable for a TCP problem. If you expect recurring network errors with your database host, maybe a local connection pooler like pgBouncer should be considered, to insulate the web environnement from these high-latency errors.

mysql_query() expects parameter 2 to be resource error in connection with remote mysql DB

My PHP code works well in connecting remote windows system mysql database and returns the output. But, when I'm using the same to connect remote linux system's mysql database, I got the following error:
"mysql_query() expects parameter 2 to be resource, boolean given in
C:\wamp\www\mysqldb.php on line 88"
That line 88 have the following content "$this->resultQur =
mysql_query($query, $this->connID);"
Help me to solve this.
yes. The resource is null in this case. But the same works in windows mysql connection. I got the error only in linux. Need to do any change for linux environment?
While putting "print mysql_error();" i got the following error
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."
The resource you're providing comes from a mysql_connect and that did not succeed!
Put error reporting on
Build some basic error handling in your script
Do not use mysql_* but mysqli_* or even better PDO with parameter binding
Output returned string from mysql_error() after your query. In that way you will see actual error.
$this->resultQur = mysql_query($query, $this->connID);
print mysql_error();
mysql_connect returns a resource on success, but a boolean "false" on error.
Your connection attempt probably failed an so the mysql_query won't be successful.
Try something like the following to see what exactly is causing the error.
mysql_connect(..) or die(mysql_error());
Additionally, it seems that the "old" mysql-library get's deprecated in PHP and it's recommended to switch to a more modern version, eg mysqli or PDO.
1 . Firstly put ini_set(‘display_errors’,1);error_reporting(E_ALL|E_STRICT); in your code at the start of the page
2 . Put Try catch around the query and print the Exception message
try { enter code here }catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
3 . Use PDO then the mysql object for query it's a modern and better approach
Use try catch around the the query and try

Do this method can blow off the 2006 mysql error

Few days back i suddenly came up with getting empty result, I was surprised and then check out the mysql_error function and then got this 2006: Mysql server has gone away. The problem is that it doesn't comes everytime, but sometimes only for the same query.
I have checked out many questions here at stackoverflow as well as many blogs on the web, but I found no possible solution for this error
Today, I wrote this function for that and the error gones away,
$conn = mysql_connect($this->host, $this->dbUser, $this->dbPass);
$db_select = mysql_select_db($this->dbName, $conn);
for($i=0;mysql_error($conn) != 2006;$i++)
{
$result = mysql_query($sql, $conn);
if($i > 10){break;}
}
I wanna ask the professionals that if it it is the proper way of getting rid of this kinda situation or it is the wrong method for that
This error will occurr when the MySQL server has been restarted / unavailable. It could be happening on a specific query if the query is causing some kind of problem (can't say more without knowing what the query does).
Either way, this error is valid and shouldn't be ignored. You need to find out WHY it is being raised in the first place.
You can use the mysql_ping function to check if the server is available before running a query rather than catching the error.

mysql Link to server lost, unable to reconnect

I get the following error:
Link to server lost, unable to reconnect
I have a mysql daemon coded, and I use mysql_pconnect to connect to mysql but after a while, I get the following error and the daemon stops functioning properly:
Link to server lost, unable to reconnect
What I do is the following:
while(true)
{
$connect = mysql_pconnect(...);
$db = mysql_select_db(...);
}
What can I do to prevent this? I need mysql connection to stay steady for the whole duration of the daemon - which may be forever.
You have a few choices.
But just as a precursor, you should try and move away from relying on mysql_* and start using the PDO instead.
Anyway...
When you open a mysql connection, it will stay "available" until the wait timeout has expired. What you are doing is constantly creating a new connection, (also without closing the other connection). This means you will either hit the server mysql limit, or your unix box socket limit very quickly.
Wait Timeout
You should first check with your server to see what this timeout is set to.
You might want to consider increasing it in your my.cnf if it is terribly low. The default period is 28800 seconds (if I recall correctly).
You can check by issuing this query:
SHOW variables like "%wait_timeout%"
You can then change the value in your my.cnf to increase it or you can also set it using
SET ##GLOBAL.wait_timeout=288000
SELECT 1
Okay, now, with a reasonable set timeout set, the "typical" way that you can make sure that you don't get the mysql has gone away message, is to just do a SELECT 1. This will do another query and make sure that the connection is held open.
And, the benefit of using the PDO is that you can then catch PDOExceptions which might be thrown when a SELECT 1 fails.
This means, that you can then try and connect again, if an exception is thrown, and then check again. If you can't connect after that then you should probably kill your daemon.
Here is some code.... you would clearly have to make your PDO object using a valid connection string.
// $pdo holds the connection and a PDO object.
try {
$pdo->execute("SELECT 1");
} catch (PDOException $e) {
// Mysql has gone away.
$pdo = null
$pdo = new PDO( $connectionString );
echo "Mysql has gone away - But we attempted to reconnect\n";
try {
$pdo->execute("SELECT 1");
} catch (PDOException $e) {
echo "Mysql has failed twice - Kill Daemon\n";
throw($e);
}
}
This is the solution that I would probably take.
You can easily substitute the SELECT 1 with your own query that you actually want to use. This is just an example.

Categories