I have set up a mod_rewrite map for apache in order to support some SEO friendly URLs. It works fine for a little while, but eventually my database connection disappears. In particular, this bit of code causes an error:
$sql = "SELECT title FROM " . MAJORS_TABLE . " WHERE cip='" . mysql_real_escape_string($cip) . "'";
$res = mysql_query($sql, $db);
if ($res) {
if (mysql_num_rows($res) >= 1) {
if ($row = mysql_fetch_assoc($res)) {
# output the new url
$url = '' . strtolower(preg_replace('#[^a-z]+#i', '-', $row['title'])) . '/' . $dir . '/'
. $cip . '/' . $sid;
$found = TRUE;
map_write_log("returning $url");
print $url . "\n";
} else {
trigger_error("major rewrite query failed to fetch a row:\n\t" . $sql, E_USER_WARNING);
}
} else {
trigger_error("major rewrite rows returned is less than 1:\n\t" . $sql, E_USER_WARNING);
}
mysql_free_result($res);
} else {
// HERE IS THE ERROR THAT IS OCCURRING
trigger_error("major rewrite query returned no resource:\n\t" . mysql_error(). "\n\t" . $sql, E_USER_ERROR);
}
My error handling routine notifies me of this error from that trigger_error call:
E_USER_ERROR; file=/var/www/mod_rewrite_maps/map_majors.php; line=60; major rewrite query returned no resource:
MySQL server has gone away
The issue basically seems to be that the database connection created when my script begins "goes away" after some time. It's probably garbage collected.
My problem is that it takes a considerable amount of time for this connection to go away so I can't just easily debug it. I'm wondering how I might detect if $db has "gone away" or is still valid so that I can reconnect. Will [man]is_resource[/man] do the trick? I tried using [man]mysql_pconnect[/man] instead of plain old [man]mysql_connect[/man] but it doesn't seem to help. It occurred to me that I might want to reconnect for every iteration of my main loop, but that seems like a real performance killer.
Any tips would be much appreciated.