Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQLi Insert Query Error - Server Has Gone Away

Tags:

php

mysql

mysqli

On trying to insert array of records, I am getting errors : 1. MySQL server has gone away 2. Error reading result set's header

Following are the details:

// DB2
$host1 = 'localhost';
$user1 = 'root';
$pass1 = '';
$db1   = 'my_db';
$conn1 = mysqli_connect($host1, $user1, $pass1, $db1);

....
...
...
...

//echo '<pre>'; print_r($countryArr); die;

$countryArr result : enter image description here

$query = "INSERT INTO `cities` (`country_id`, `city`, `soft_delete`, `date_added`) VALUES " . implode(',', $countryArr);
mysqli_query($conn1, $query);

Error : enter image description here

like image 396
Kunwarbir S. Avatar asked Mar 22 '26 04:03

Kunwarbir S.


2 Answers

MySQL server has gone away may be due to exceeding limit on mysql packet size. Check MySQL variable max_allowed_packet and try to increase it.

like image 157
Vasiliy Zverev Avatar answered Mar 24 '26 19:03

Vasiliy Zverev


Step 1:

set_time_limit(0); // this will remove the time limit if any.

Step 2:

Also check ping to keep the connection alive, http://php.net/manual/en/mysqli.ping.php

Step 3

Try executing the inserts in batches. i.e Batch of 500 statements.

like image 36
Fakhruddin Ujjainwala Avatar answered Mar 24 '26 17:03

Fakhruddin Ujjainwala