Lost connection to MySQL server during query rows

While working on a project today a script I had that turns a database into a simple tab delimited file stopped working and was producing the following error:

Lost connection to MySQL server during query rows

Google searching didn’t turn up anything useful because most people said just to “use mysqldump instead” which wasn’t really an option for me. After running analyze, repair and optimize table and using phpMyAdmin to make a copy of the table I was pretty confident that it wasn’t a corruption problem so I added the following bit of code around what I already had:

 

define(‘C_NUM_PER_LIMIT’, 100000);

$iteration = 0;

do
{
$limit_from = C_NUM_PER_LIMIT * $iteration; $iteration++;

$sql = “SELECT * FROM `table` ORDER BY `id` LIMIT $limit_from, ” . C_NUM_PER_LIMIT;
$res = mysql_query($sql);
// way more stuff

} while (mysql_num_rows($res) > 0);

I hope this helps. :)

Got a packet bigger than ‘max_allowed_packet’ bytes

Ran in to this problem today at work so I’m just making a note of it for future reference. I was running a PHP script crawler today that was inserting the downloaded data into a MySQL database and the script crash with an error:

Got a packet bigger than ‘max_allowed_packet’ bytes

The simple fix was to add in the code:

$sql = "SET GLOBAL max_allowed_packet=16*1024*1024;"; // 16 * 1 MB
mysql_query($sql);

Hope this helps someone else as well. :)