I’m writing a console application with Yii, and encountered the MySQL Server has gone away error. This is related to using PHP’s pcntl_fork(), which makes PHP lose its MySQL connection after a while in the child processes.
The Yii solution is very easy, but I thought I might share it anyway for people who’d encounter the same issue:
This basically closes the connection before forking, and reinstantiates it in the child and parent after the fork. By doing that, the error disappears and you can continue to use everything you had already collected from the db
The issue is that the child process inherits the database connection. The common practice is to reinitiate the database connection in the parent process after we forked off a child.
$pid = pcntl_fork();
if($pid == -1){
//Problem launching the job
die();
}
elseif ($pid){
// Parent process
// child inherits parents db connection so we have to reconnect
$this->reconnect();
//do whatever
}
else {
//Forked child, do your deeds, database connection active
// exec child code
// finish
exit();
}
However, this has nothing to do with yii, and you have to reconnect to the database