php, mysql server has gone away - php

What is wrong, when you connect to the DB on the LINE BEFORE THE QUERY, and you still get "MySQL server has gone away"?
check this example code:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
$ids[] = $data[id];
}
foreach ($ids as $id) {
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
mysql server is gone away, i get that in the foreach loop.
BTW i need to connect in the foreachloop, because it may take along time before it finds something to update (like 1-2 minutes), and then for sure i will get mysql server has gone away.

I assume your issue is that the script may execute for a very long time before sending the first UPDATE query.
You should check the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"
You can also try to piece of code to do a reconnect:
if (!mysql_ping ($conn)) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close($conn);
$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);
}
Combining with your code it would be:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
if (!mysql_ping ()) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close();
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
}
$ids[] = $data['id'];
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}

We got that error this week at work here is the official documentation from MySQL : http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
This section also covers the related Lost connection to server during query error.
The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection.

Related

Why won't my JSON array query work?

Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).

PHP MYSQL Access denied for user Error [duplicate]

This question already has answers here:
Unable to connect to database: Access denied for user ''#'localhost' to database 'socialdb'
(6 answers)
Closed 9 years ago.
I'm trying to get the 'Content' value from a specific row ID in mySql, I echoed the result in PHP, But i got "Access denied for user ''#'localhost' (using password: NO)".
I tryed to check my query in phpMyAdmin, and i got the exact result I expected for.
Here is my code:
$con = mysql_connect("localhost", "XXX", "XXX") or die (mysql_error());
$db = mysql_select_db("XXX", $con) or die (mysql_error());
function head($d) {
$query = mysql_query("SELECT Content FROM list WHERE ID = '$d'") or die(mysql_error());
$post = mysql_fetch_assoc($query);
echo $post["Content"];
}
<h1> <?php head(1); ?> </h1>
Thank you so much.
The error message you quote sounds like the database isn't connected yet when you're making the call. If no connection exists, mysql_query() will try to establish a connection with default values (which usually are empty).
You should check your program flow and make sure you are actually connected to the database before making any queries.
move your first two lines to your function:
function head($d) {
$con = mysql_connect("localhost", "XXX", "XXX") or die (mysql_error());
$db = mysql_select_db("XXX", $con) or die (mysql_error());
$query = mysql_query("SELECT Content FROM list WHERE ID = '$d'") or die(mysql_error());
$post = mysql_fetch_assoc($query);
echo $post["Content"];
}
<h1> <?php head(1); ?> </h1>
issue is with
mysql_connect("localhost", "ncode_hana", "NOAM7778")
chech that sqn user and pass are correct and this user has right over your selected db...
also, never share your orignial user ID and password with anyone..
also, as Pekka told you need something like this
<h1> <?php include('yourdatabaseconnectionfile.php'); ?> <?php head(1); ?> </h1>
ALTERNATIVELY
<?php
$con = mysql_connect("localhost", "XXX", "XXX") or die (mysql_error());
$db = mysql_select_db("XXX", $con) or die (mysql_error());
<h1> <?php head(1); ?> </h1>
function head($d) {
$query = mysql_query("SELECT Content FROM list WHERE ID = '$d'") or die(mysql_error());
$post = mysql_fetch_assoc($query);
echo $post["Content"];
}
ONE MORE OPTION
add connection string in function (not recommended though)
function head($d) {
mysql_connect("localhost", "ncode_hana", "NOAM7778");
$query = mysql_query("SELECT Content FROM list WHERE ID = '$d'") or die(mysql_error());
$post = mysql_fetch_assoc($query);
echo $post["Content"];
}

My php script is not using given username/pass/host rather using root#localhost (password: NO)

Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)

Any reason why this MySQL query wouldn't run?

I have the following PHP script setup to run as a cron job every minute:
<?php
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
die("Database error");
}
mysql_query("TRUNCATE TABLE contact_ips");
mysql_close($con);
die();
?>
This script is to prevent a contact form being submitted from the same IP address more than once within 1 minute. Therefore, it should clear the contents of the table that submitted the form and it is not doing that.
Could it be my cron command that is working correctly?
Thanks
First of all, mysql_query is deprecated. Use mysqli instead.
Second, it seems like you might want to set a variable to the query, eg $result = mysqli_query() so you can do post-processing.
Have you tried adding a die() to the mysql query to check that that query is running?
Also, it seems like you haven't selected a DB. Add this after the connection code. mysql_select_db("databaseName", $con);
It should be
<?php
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
die("Database error");
}
mysql_select_db("database", $con);
mysql_query("TRUNCATE TABLE contact_ips");
mysql_close($con);
die();
?>

mysql_fetch_object(): supplied argument is not a valid MySQL result resource

I'm trying to set a simple cron script to do some database updating, and I'm pretty worthless with MySQL without ActiveRecord (I use CodeIgniter). I keep getting the error message,
mysql_fetch_object(): supplied argument is not a valid MySQL result resource
with the following code:
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$query = "select visit_e_id, visit_e_type from visits";
$result = mysql_query($query)
or die("Query failed: ".mysql_error()." Actual query: ".$query);
while($row=mysql_fetch_object($result))
{
....
}
Like I said, I'm not that great with straight PHP and MySQL (would appreciate any advice on how to include some sort of framework or ActiveRecords that could be used as part of a cron job). Any thoughts?
What happens if you assign mysql_connect as a variable and pass it in as a link identifier as a second parameter to the mysql_select_db and query functions?
$db = mysql_connect("localhost", "user", "pass") or die(mysql_error());
// Check to see if valid connection
var_dump($db);
mysql_select_db("my_db", $db) or die(mysql_error());
$query = "select visit_e_id, visit_e_type from visits";
$result = mysql_query($query, $db)
or die("Query failed: ".mysql_error()." Actual query: ".$query);
while($row=mysql_fetch_object($result))
{
....
}
Also ensure that you query syntax is correct and doesn't have misspelling or typos
This error is pretty simple and self-explanatory - a $result variable has unexpected type.
Thus, you have to so some debugging. Add var_dump($result); before and inside loop and study the output.

Categories