Database connection problems in PHP/MySQL - php

When I run the script below with the added line,
$count = 1;
I get a value of 1 on the screen, but when I take that line out I don't get get anything at all. tried moving it above the $count=mysql_num_rows($result); and I still didn't get a value.
$sql="SELECT EMAIL FROM CUSTOMER WHERE email='$myemail' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$count = 1;
echo $count;
What am I doing wrong here? I have never used PHP until now. The error is:
Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2)

This means that your MySQL server socket (/var/run/mysqld/mysqld.sock) is either missing or corrupt.
It could also mean that MySQL service is not working right, try restarting in SSH using:
$ service mysqld restart
If it says the service is missing, then say:
$ service mysql restart

I would guess at an a error with your SQL query (var_dump($count); would return false in this case).
To check this, I would do 2 things:
After your query do if(!$result) echo mysql_error( ); - this will show you any errors that happen while talking to the database
To check your SQL is being formed correctly, create it in a variable (e.g. $sql = "SELECT email ...";) and echo it out.
EDIT: Ahh just seen the update - it's a connection issue. Check that your mysql_connect( ) has the right host, username & password. Otherwise it could be a problem on your system (e.g. firewall or similar)
EDIT 2: As has been rightly pointed out, mysql_connect details would cause a different connection error to the one you're seeing. I've had a quick Google for it, and this cropped up http://lists.mysql.com/mysql/204035. Not sure it'll be any use as I've not read it through, but it does describe some steps for the solving this problem on someone else's system.

When you can't connect successfully to the database, return value from mysql_query function ($result) would not be a valid value. so when you give it to mysql_num_rows function, it fails & returns FALSE value, which has no visual effect on output screen!

Related

php connect to mysql db in cloud 9?

I usually connect php to mysql with localhost in my PC..
now i'm trying to put my project in cloud https://c9.io ,but i can't connect to mysql. i already have mysql database in cloud and put my project in same place...
mysql_connect("/lib/mysql/socket/mysql.sock","myUser","") or die(mysql_error());
i use script above to connect but i get Unknown MySQL server host '/lib/mysql/socket/mysql.sock' (1)
what shoul i do ?
Okay, so none of the above answers had worked for me, but fortunately I was able to setup a database and get it up and running my own way and I can now make queries and run them successfully, so I will share my method with you in hopes that anyone else scouring the internet can stumble across this and not have to go through the same head scratching that I did.
If you want the quick rundown, just scroll to Step 3 and read on from there. If you're a complete beginner, keep reading as I'll walk you through it in detail.
Couple things to mention:
You will have to setup a database via a Terminal in Cloud 9. I had no experience prior doing it in a Terminal before, but it's very simple to learn.
You can not use mysql functions, you have to use mysqli, since mysql functions are deprecated and Cloud 9 will not run them.
Step 1: Setup MySQL on Cloud 9 (in Terminal)
In your project, open up a New Terminal (click the plus-sign tab above the text editor space, select "New Terminal"). In the terminal, type mysql-ctl start and hit Enter. MySQL will start up in the back, but you won't get any response back in the terminal.
Next, type mysql-ctl cli and hit Enter. You should see some text that starts off as Welcome to the MySQL monitor.... Congrats, you've setup MySQL on your Cloud 9 project.
Step 2: Create a test database (in Terminal)
You can actually go ahead and create your official database if you like, but for this sake I'll just make a database that holds a table that holds an ID and a username. So here's the steps to setting up a database and a table. If you've used MySQL and databases before, then this should be cake, but I'll explain it in detail for those who might not fully understand MySQL .
Type SHOW DATABASES; and hit Enter. This will show a list of current databases within your project. You can enter this any time you want to see a list of your databases on the current project.
Type in CREATE DATABASE sample_db; and hit Enter. You should get a Query OK, 1 Row affected. which means the query was successful. You can name the database whatever you like, but for this little walk-through, I named it sample_db.
Type in USE sample_db; and hit Enter. This selects sample_db from the list of databases.
Type in CREATE TABLE users (id INT(11), username VARCHAR(20));, and hit Enter. This creates a table named users with two columns: id and username. The number in parentheses represents the character limit the column will store in the database. In this case for example, username won't hold a string longer than 20 characters in length.
Type in INSERT INTO users (id, username) VALUES (1, "graham12");, and hit Enter. This will add the id of 1 and a username graham12 in the table. Since the id column is an INT, we do not put quotes around it.
Type in SELECT * FROM users;, and hit Enter. This will show everything that is in the users table. The only entry in there should be what we inserted from the last step we just did.
Step 3: Get the credentials you'll need to connect to the database from PHP. (in Terminal)
Now we have some data in our table that we can test our mysqli connection with. But first, we have to get the credentials we will need to connect to the database in PHP. In Cloud 9, we will need 5 credentials to connect:
Host name
Username
Password
Database name
Port #
Username, password, database name, and port #, are practically already known to you by now. I'll explain:
Host name - Type in SHOW VARIABLES WHERE Variable_name = 'hostname';, and hit Enter. You'll get a table that has 2 columns: Variable_name and Value. In the Value column you should see something like yourUsername-yourProjectName-XXXXXXX, where the X's are a 7 digit number. Write this number down or save it some where. This is your host name. (If you're getting the quick rundown on this walkthrough, just start a new terminal and start up your mysql and select the database you want to use, then type in SHOW VARIABLES WHERE Variable_name = 'hostname';. Re-read this step from the beginning if you're confused.)
Username - Your username that you use to log in to Cloud 9.
Password - There is NO password for your database in Cloud 9.
Database name - This would be sample_db or whatever you named your database;
Port # - is 3306. In Cloud 9, all of your projects are wired to 3306. This is a universal constant of Cloud 9. It will not be anything else. Write this as you would an integer, not as a string. mysqli_connect() will interpret the port # as a long data type.
Last Step: Connect to the database with PHP! (using PHP)
Open up a PHP file and name it whatever you like.
I'll pretend that my host name is graham12-sample_db-1234567 for this example and that this is what my data looks like:
Host name: "graham12-sample_db-1234567"
Username: "graham12"
Password: ""
Database name: "sample_db"
Port #: 3306
So in PHP, insert your credentials accordingly:
<?php
//Connect to the database
$host = "grahamsutt12-sample_db-1234567"; //See Step 3 about how to get host name
$user = "grahamsutt12"; //Your Cloud 9 username
$pass = ""; //Remember, there is NO password!
$db = "sample_db"; //Your database name you want to connect to
$port = 3306; //The port #. It is always 3306
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
//And now to perform a simple query to make sure it's working
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "The ID is: " . $row['id'] . " and the Username is: " . $row['username'];
}
?>
If you get a result and no error then you have successfully setup a database and formed a connection to it with PHP in Cloud 9. You should now be able to make all the queries you can normally make.
Note: I demonstrated the last part without using parameterized queries for the sake of being simple. You should always use parameterized queries when working with real web applications. You can get more info on that here: MySQLi Prepared Statements.
For starters, the mysql_* functions are deprecated so you shouldn't be using them. Look at PDO or mysqli instead. Next, you'll want to try this per the example docs:
$link = mysql_connect('localhost:/lib/mysql/socket/mysql.sock', 'myUser', '') or die(mysql_error());
To find the ip running you project, create a test file with the code below, run it and put the result as host.
<?php
$ip = getenv("REMOTE_ADDR") ;
Echo "Your IP is " . $ip;
?>
You are using Cloud9 so it's a little different to use. To connect to MySQL you have to first create the MySQL server in C9. Type this in C9's command line:
mysql-ctl start
C9 will create your mysql server.
MySQL 5.1 database added. Please make note of these credentials:
Root User: <username>
Database Name: c9
Next to find your IP address type:
echo $IP
Now use this code with your username, the ip address, no password and the 'c9' database to access MySQL:
mysql_connect("<$IP>","<username>","") or die(mysql_error());
mysql_select_db("c9")
Hope this helps
The documentation show how start, stop, and run the mysql environment.
Start the MySQL shell mysql-ctl start then in yor file.php:
$ip = getenv("REMOTE_ADDR");
$port = "3306";
$user = "YorUsername";
$DB = "c9";
$conn = mysql_connect('$ip', '$user', '', '$db', '$port')or die(mysql_error());
mysql_select_db('$db','$conn')or die(mysql_error());
mysql_query("select * from YourTableName",'$conn')or die(mysql_error());
The line getenv("REMOTE_ADDR") return the same local IP as the application you run on Cloud9.

SQL Server stored procedure not working in PHP

I have a problem getting a SQL Server stored procedure to work using PHP. My code is below. The stored procedure is expecting an integer to be passed to it. The message that displays is "Stored procedure error". This shows the connection is working. I'm not sure what's wrong. Can someone help me out? Thanks.
$db_connection = sqlsrv_connect($servername, $connectOpts);
if($db_connection === false) {
echo ("Error connecting to the database.");
exit;
}
$sp_command = "EXEC usp_testsp #valint=?";
$sp_vals = array( array("3", SQLSRV_PARAM_IN));
$sp_execute = sqlsrv_query($db_connection, $sp_command, $sp_vals);
if($sp_execute === false) {echo('Stored procedure error');}
else {echo('Success');}
sqlsrv_close($db_connection);
I don't see anything wrong with your code so I think your problem might be in your database itself. I can think of two possibilities.
Your stored procedure is written incorrectly. If that's the case you should post the stored procedure here so we can look it over.
Your stored procedure security settings aren't correct. You need to set the security settings inside SQL Server Management Studio. Off hand, I can't remember the exact path to set the security settings but it's something like: Right click on usp_testsp - properties - security. Then set the stored procedure with the database login information.

Is there any error logging when mysql query fails?

I'm curious if there is any error logging by the MySQL database when I execute a query. I know that I call mysql_error to retrieve an error but is there some other logging on database side?
By default mysql does not log queries. But you can increase the log level at the sql configuration files. Try the file: /etc/mysql/my.cnfand uncomment the line
general_log = 1
For performance, it is off by default.
Well, if it's properly set up, then it should be. It usually is by default. You can get more info in the MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/server-logs.html
Also, if you use *nix or BSD, the logs are usually stored in /var/log/ .
what do you mean like empty querys or bad querys?
$sql = mysql_query( select * from table );
// but theres no rows you would right a if statment with mysql_num_rows
if(mysql_num_rows($sql) > 0){
}else{
// error message here for empty
}
// or
mysql_query(......)or die(mysql_error());
// this will tell you why its returnig false!

mysql_insert_id() stopped working after PHP update

I am preparing to update a live web server from PHP 5.2.12 to 5.3.5. In preparation, I have performed the update on a second server which is a mirror of the live one ("dev" server). Both servers are using FreeBSD, and both used ports to install PHP and MySQL. The live server is using MySQL 5.0.89, the newly upgraded dev server is using 5.1.54.
The following code executes as expected on the live server (PHP 5.2.12/5.0.89), returning the value of the AUTO_INCREMENT row that was just inserted. This function is part of a database class that is used throughout the site, where "$this->_private['cn']" is the resource link.
public function insert ($sql=false) {
#mysql_select_db($this->_private['db_name'], $this->_private['cn']);
$res = null;
if (false !== $sql) {
$query_obj = mysql_query($sql, $this->_private['cn']);
if ($query_obj)
$res = mysql_insert_id($this->_private['cn']);
}
return $res;
}
On the dev server (5.3.5/5.1.54), the return is zero. Note - not null (which is returned if the query fails), but ZERO. I can look at the table and verify that a new row has in fact been inserted, and the auto increment field has properly advanced. The field value is currently at 121288, so it is well within PHP's integer range. I've even re-created the class's code on a simple page and get the same result. mysql_error() indicates no failures. Error reporting is set to E_ALL, not a peep there.
ARGH! Any ideas?
see this bug which recommends following your query with SELECT LAST_INSERT_ID()

MySQL server has gone away - in exactly 60 seconds

I recently discovered that a sql query that was running fine earlier is now timing out after 60 seconds and throwing an error. The query is slow but runs as part of a nightly job so that's not a problem in itself (so please don't suggest I optimize it).
I'm able to reproduce the error consistently by running "select SLEEP(120);" from PHP as shown below. However, running the same statement from a MySQL client is successful (returns 0). I've tried adjusting wait_timeout (set to 28800), but have had no luck. I've also rebooted both the db server and machine itself.
The fact that it always times out at exactly 60 seconds suggests to me that it is likely to be a setting and not a limited resources issue.
I'm running:
Windows Server 2003
MySql 5.1.36-community
PHP 5.3
Below are my test code, the output and the results from SHOW VARIABLES
Thanks!
CODE:
set_error_handler("sqlErrorHandler");
set_time_limit(12000);
$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);
echo "mysql_ping = " . (mysql_ping($link) ? "LIVE" : "DEAD") . "<br /><br />";
$sql = "SELECT SLEEP(120);";
$start = microtime(true);
mysql_query($sql, $link);
echo "**query done**<br />";
allDone();
function allDone(){
global $start, $sql;
$end = microtime(true);
echo "sql : $sql<br />";
echo "elapsed : " . ($end - $start) . "<br />";
echo "<br />";
}
function sqlErrorHandler($errno, $errstr, $errfile, $errline){
global $link;
echo "Error : $errno<br />$errstr<br />";
echo "mysql_ping : " . (mysql_ping($link) ? "LIVE" : "DEAD") . "<br />";
echo "<br />";
allDone();
}
OUTPUT :
mysql_ping = LIVE
Error : 2
mysql_query() [function.mysql-query]: MySQL server has gone away
mysql_ping : DEAD
sql : SELECT SLEEP(120);
elapsed : 60.051116943359
Error : 2
mysql_query() [function.mysql-query]: Error reading result set's header
mysql_ping : DEAD
sql : SELECT SLEEP(120);
elapsed : 60.0511469841
**query done**
sql : SELECT SLEEP(120);
elapsed : 60.051155090332
SHOW VARIABLES:
Variable_name=Value
auto_increment_increment=1
auto_increment_offset=1
autocommit=ON
automatic_sp_privileges=ON
back_log=50
basedir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\
big_tables=OFF
binlog_cache_size=32768
binlog_format=STATEMENT
bulk_insert_buffer_size=8388608
character_set_client=utf8
character_set_connection=utf8
character_set_database=latin1
character_set_filesystem=binary
character_set_results=utf8
character_set_server=latin1
character_set_system=utf8
character_sets_dir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\share\\charsets\\
collation_connection=utf8_general_ci
collation_database=latin1_swedish_ci
collation_server=latin1_swedish_ci
completion_type=0
concurrent_insert=1
connect_timeout=10
datadir=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\
date_format=%Y-%m-%d
datetime_format=%Y-%m-%d %H:%i:%s
default_week_format=0
delay_key_write=ON
delayed_insert_limit=100
delayed_insert_timeout=300
delayed_queue_size=1000
div_precision_increment=4
engine_condition_pushdown=ON
error_count=0
event_scheduler=OFF
expire_logs_days=0
flush=OFF
flush_time=1800
foreign_key_checks=ON
ft_boolean_syntax=+ -><()~*:""&|
ft_max_word_len=84
ft_min_word_len=4
ft_query_expansion_limit=20
ft_stopword_file=(built-in)
general_log=OFF
general_log_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.log
group_concat_max_len=1024
have_community_features=YES
have_compress=YES
have_crypt=NO
have_csv=YES
have_dynamic_loading=YES
have_geometry=YES
have_innodb=YES
have_ndbcluster=NO
have_openssl=DISABLED
have_partitioning=YES
have_query_cache=YES
have_rtree_keys=YES
have_ssl=DISABLED
have_symlink=YES
identity=0
ignore_builtin_innodb=OFF
init_connect=
init_file=
init_slave=
innodb_adaptive_hash_index=ON
innodb_additional_mem_pool_size=2097152
innodb_autoextend_increment=8
innodb_autoinc_lock_mode=1
innodb_buffer_pool_size=96468992
innodb_checksums=ON
innodb_commit_concurrency=0
innodb_concurrency_tickets=500
innodb_data_file_path=ibdata1:10M:autoextend
innodb_data_home_dir=D:\\MySQL Datafiles\\
innodb_doublewrite=ON
innodb_fast_shutdown=1
innodb_file_io_threads=4
innodb_file_per_table=OFF
innodb_flush_log_at_trx_commit=1
innodb_flush_method=
innodb_force_recovery=0
innodb_lock_wait_timeout=50
innodb_locks_unsafe_for_binlog=OFF
innodb_log_buffer_size=1048576
innodb_log_file_size=19922944
innodb_log_files_in_group=2
innodb_log_group_home_dir=.\\
innodb_max_dirty_pages_pct=90
innodb_max_purge_lag=0
innodb_mirrored_log_groups=1
innodb_open_files=300
innodb_rollback_on_timeout=OFF
innodb_stats_on_metadata=ON
innodb_support_xa=ON
innodb_sync_spin_loops=20
innodb_table_locks=ON
innodb_thread_concurrency=8
innodb_thread_sleep_delay=10000
innodb_use_legacy_cardinality_algorithm=ON
insert_id=0
interactive_timeout=28800
join_buffer_size=131072
keep_files_on_create=OFF
key_buffer_size=50331648
key_cache_age_threshold=300
key_cache_block_size=1024
key_cache_division_limit=100
language=C:\\Program Files\\MySQL\\MySQL Server 5.1\\share\\english\\
large_files_support=ON
large_page_size=0
large_pages=OFF
last_insert_id=0
lc_time_names=en_US
license=GPL
local_infile=ON
log=OFF
log_bin=OFF
log_bin_trust_function_creators=OFF
log_bin_trust_routine_creators=OFF
log_error=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.err
log_output=FILE
log_queries_not_using_indexes=OFF
log_slave_updates=OFF
log_slow_queries=OFF
log_warnings=1
long_query_time=10.000000
low_priority_updates=OFF
lower_case_file_system=ON
lower_case_table_names=1
max_allowed_packet=1048576
max_binlog_cache_size=4294963200
max_binlog_size=1073741824
max_connect_errors=10
max_connections=800
max_delayed_threads=20
max_error_count=64
max_heap_table_size=16777216
max_insert_delayed_threads=20
max_join_size=18446744073709551615
max_length_for_sort_data=1024
max_prepared_stmt_count=16382
max_relay_log_size=0
max_seeks_for_key=4294967295
max_sort_length=1024
max_sp_recursion_depth=0
max_tmp_tables=32
max_user_connections=0
max_write_lock_count=4294967295
min_examined_row_limit=0
multi_range_count=256
myisam_data_pointer_size=6
myisam_max_sort_file_size=107374182400
myisam_recover_options=OFF
myisam_repair_threads=1
myisam_sort_buffer_size=12582912
myisam_stats_method=nulls_unequal
myisam_use_mmap=OFF
named_pipe=OFF
net_buffer_length=16384
net_read_timeout=30
net_retry_count=10
net_write_timeout=80
new=OFF
old=OFF
old_alter_table=OFF
old_passwords=OFF
open_files_limit=2048
optimizer_prune_level=1
optimizer_search_depth=62
optimizer_switch=index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on
pid_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.pid
plugin_dir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib/plugin
port=3306
preload_buffer_size=32768
profiling=OFF
profiling_history_size=15
protocol_version=10
pseudo_thread_id=3230
query_alloc_block_size=8192
query_cache_limit=1048576
query_cache_min_res_unit=4096
query_cache_size=33554432
query_cache_type=ON
query_cache_wlock_invalidate=OFF
query_prealloc_size=8192
rand_seed1=
rand_seed2=
range_alloc_block_size=4096
read_buffer_size=65536
read_only=OFF
read_rnd_buffer_size=262144
relay_log=
relay_log_index=
relay_log_info_file=relay-log.info
relay_log_purge=ON
relay_log_space_limit=0
report_host=
report_password=
report_port=3306
report_user=
rpl_recovery_rank=0
secure_auth=OFF
secure_file_priv=
server_id=0
shared_memory=OFF
shared_memory_base_name=MYSQL
skip_external_locking=ON
skip_networking=OFF
skip_show_database=OFF
slave_compressed_protocol=OFF
slave_exec_mode=STRICT
slave_load_tmpdir=C:\\WINDOWS\\TEMP
slave_net_timeout=3600
slave_skip_errors=OFF
slave_transaction_retries=10
slow_launch_time=2
slow_query_log=OFF
slow_query_log_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1-slow.log
sort_buffer_size=262144
sql_auto_is_null=ON
sql_big_selects=ON
sql_big_tables=OFF
sql_buffer_result=OFF
sql_log_bin=ON
sql_log_off=OFF
sql_log_update=ON
sql_low_priority_updates=OFF
sql_max_join_size=18446744073709551615
sql_mode=
sql_notes=ON
sql_quote_show_create=ON
sql_safe_updates=OFF
sql_select_limit=18446744073709551615
sql_slave_skip_counter=
sql_warnings=OFF
ssl_ca=
ssl_capath=
ssl_cert=
ssl_cipher=
ssl_key=
storage_engine=InnoDB
sync_binlog=0
sync_frm=ON
system_time_zone=Eastern Daylight Time
table_definition_cache=256
table_lock_wait_timeout=50
table_open_cache=619
table_type=InnoDB
thread_cache_size=38
thread_handling=one-thread-per-connection
thread_stack=196608
time_format=%H:%i:%s
time_zone=SYSTEM
timed_mutexes=OFF
timestamp=1256827484
tmp_table_size=16777216
tmpdir=C:\\WINDOWS\\TEMP
transaction_alloc_block_size=8192
transaction_prealloc_size=4096
tx_isolation=REPEATABLE-READ
unique_checks=ON
updatable_views_with_limit=YES
version=5.1.36-community
version_comment=MySQL Community Server (GPL)
version_compile_machine=ia32
version_compile_os=Win32
wait_timeout=28800
warning_count=0
The php option mysql.connect_timeout is the reason for this. It's not only used for connect timeout, but as well as waiting for the first answer from the server. You can increase it like this:
ini_set('mysql.connect_timeout', 300);
ini_set('default_socket_timeout', 300);
When I ran into this problem, it wasn't caused by wait_timeout (which was set to the default 8 hours) but by max_allowed_packet with a large INSERT statement. Changing max_allowed_packet from PHP had no effect, but when I changed it in the mysqld section of /etc/my.cnf and restarted the MySQL server, the problem disappeared.
There's a whole bunch of things that can cause this. I'd read through these and try each of them
http://dev.mysql.com/doc/refman/5.1/en/gone-away.html
I've worked for several web hosting companies over the years and generally when I see this, it is the wait_timeout on the server end though this doesn't appear to be the case here.
If you find the solution, I hope you post it. I'd like to know.
This is something I do, (but usually with the MySQLi class).
$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);
// RUN REALLY LONG QUERY HERE
// Reconnect if needed
if( !mysql_ping($link) ) $link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass", true);
// RUN ANOTHER QUERY
Increasing SQL-Wait-Timeout worked for me in this case, try this:
mysql_query("SET ##session.wait_timeout=900", $link);
before you first "normal" SQL queries.
My case was a database corruption after a minor upgrade in mysql basically 5.0.x to 5.1.x
with the DB in myisam.
The same lines on query:
MySQL server has gone away
Error reading result set's header
After repairing & optimizing it with mysqlcheck, it returned to normal, without the need to change the socket timeout.
I solved this problem with
if( !mysql_ping($link) ) $link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass", true);
I have the same problem with mysqli.
My solution is https://www.php.net/manual/en/mysqli.configuration.php
mysqli.reconnect = On
I noticed something perhaps relevant.
I had two scripts running, both doing rather slow queries. One of them locked a table and the other had to wait. The one that was waiting had default_socket_timeout = 300. Eventually it quit with "MySQL server has gone away". However, the mysql process list continued to show both query, the slow one still running and the other locked and waiting.
So I don't think mysqld is the culprit. Something has changed in the php mysql client. Quite possibly the default_socket_timeout which I will now set to -1 to see if that changes anything.
In our case, the culprit was the global (not "local") MySQL variable "wait_timeout".
Compare the results of the following queries:
SHOW VARIABLES LIKE '%wait%';
to
SHOW GLOBAL VARIABLES WHERE Variable_name LIKE '%wait%';
In our case the first query showed a wait_timeout of 28800, but the 2nd query showed a value of 10 (seconds).
We verified that changing the global variable fixed the problem. Here is a simple PHP script that reproduced our condition:
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
sleep(10); // number of seconds to sleep
// MySQL server has gone away?
$obj = mysqli_query($db, 'SELECT * FROM some_table');
$results = mysqli_fetch_object($obj);
print_r($results);
As soon as the sleep time exceeded the global wait_timeout value, we would get the error: "Warning: mysqli_query(): MySQL server has gone away".
To change the value, we had to edit the setting in our Amazon RDS dashboard.
I had this problem recently. I stumbled across an option: default_authentication_plugin
For some reason it had set it to caching_sha2_password, but updating the value to mysql_native_password fixed it for me. I'm not sure what the differences are, though, so be careful!
Hope this helps someone!
I was having trouble on a database restore using mysqldumper (php program). I was able to get it working by changing the "mssql.timeout" setting in the php.ini. It was defaulted to 60 and I changed it to 300.
By my experiences when it happens on light queries there is a way to solve the problem. It seems when you start or restart mysql after apache this problem starts to appear and the source of the problem is confused open sockets in the php process.
To solve it:
First restart mysql service
Then restart apache service
It happens if the connection was open for quite sometime but no action was done in the MySQL server. In that case, connection timeout occurs with the error "MySQL server has gone away". The answers above may work and may not work. Even the accepted answer did not work for me. So I tried a trick and it worked fine for me. Logically, in order to avoid this error, we have to keep the MySQL connection running or in short, keep it alive. Assume that we are trying to Bulk insert 250k records. Generally it takes time to create parse data from somewhere and make Bulk query and then insert. In this scenario, most of us use a loop to create the SQL string. So let's count the iteration number and make a dummy database call after a certain iteration. It will keep the connection alive.
for(int i = 0, size = somedatalist.length; i < size; ++i){
// build the Bulk insert query string
if((i%10000)==0){
// make a dummy call like `SELECT * FROM log LIMIT 1`
// it will keep the connection alive
}
}
// Execute bulk insert
Please see this link http://bugs.php.net/bug.php?id=45150
seems like they moved to native MYSQL support in PHP5.3 and it has some trouble working with IPV6.
Try using "127.0.0.1" instead of "localhost"

Categories