There appears to be a disconnection issue with the PHP Zend Framework 2 and

Hey there, I have a PHP daemon set up to manage requests from RabbitMQ.

However, after running for a day, it stops functioning due to encountering the error "MySQL has gone away."

PHP Warning:  PDOStatement::execute(): MySQL server has gone away in /var/www/daemon/www/vendor/zendframework/zendframework/library/Zend/Db/Adapter/Driver/Pdo/Statement.php on line 239
PHP Warning:  PDOStatement::execute(): Error reading result set\'s header in /var/www/daemon/www/vendor/zendframework/zendframework/library/Zend/Db/Adapter/Driver/Pdo/Statement.php on line 239

I opted not to use Doctrine and instead passed my \Zend\Db\Adapter\Adapter to a database wrapper class with the following function:

public static function executeScalar($statement, $parameters, \Zend\Db\Adapter\Adapter $dbAdapter)
{
    // Function code here...
}

The `DbResult` is a custom class that wraps database results to check for errors, empty results, row count, etc.

Shown below is my `database.local.php` configuration file:

return array(
    'service_manager' => array(
        'factories' => array(
            'mysql' => function ($sm)
            {
                return new Zend\Db\Adapter\Adapter(array(
                    // Database configurations here...
                ));
            },
        )
    )
)

Whenever I need to execute SQL queries, I follow this pattern within my controller or other classes:

$service = $this->getServiceLocator();
$dbAdapter = $service->get('mysql');
$get = \Db\Database::executeScalar('SELECT * FROM mytable WHERE id <= ?', array(10), $dbAdapter); 

Unfortunately, I am unable to catch the warning messages. Is there a way to force reconnect or should I disconnect after each request?

Would the following strategy work to handle the error?

$dbAdapter->getDriver()->getConnection()->connect();

At the end of the request, would this be sufficient?

$dbAdapter->getDriver()->getConnection()->disconnect();

Answer №1

Indeed, I do enable the persistent connection option, although I don't particularly like it.

I've identified the issue - it's caused by the MySQL server closing idle connections after a 'wait timeout'. When MySQL shuts down the idle connection, PDO doesn't receive any notification, resulting in a "MySQL has gone away" error the next time you run a query.

For HTTP requests, this behavior is acceptable because once the server responds to the request, PHP execution stops/exits, thereby closing all connections to the database.

However, for daemons/services, this isn't ideal as they often wait for client requests (remain idle). My workaround is to close the connection every time it finishes handling a client request. For example:

while (true) {
    //listen to rabbitmq queue
    //...

    //perform actions based on client requests from rabbitmq queue
    //...

    //close the connection whether it's currently using the database or not
    //the connection will be re-established when we call $service->get('mysql');
    $service = $this->getServiceLocator();
    $dbAdapter = $service->get('mysql');
    $dbAdapter->getDriver()->getConnection()->disconnect();
}

Answer №2

While creating a persistent connection to your database can be tempting, it is important to note that it may not always be the best solution right off the bat. It is advisable to do some thorough research on this topic before proceeding with it. For more information and documentation, you can refer to the link below:

http://php.net/manual/en/pdo.connections.php#example-954

Additionally, it is crucial to review the queries being executed to ensure that the "gone away" message is not triggered by the MySQL server receiving an excessively large packet (e.g., inserting a large blob). This could result in the connection unexpectedly closing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to setting an array for session variable and saving data into the database within Joomla

I am currently working on a project in Joomla where I need to retrieve user input from textboxes and store it into session variables. However, I am facing difficulties when it comes to retrieving the session values and storing them into a database because ...

unable to successfully unlink after completing the FTP upload

I encountered an issue with two unlink functions in my class. The first one, located in the moveSub() method after move_uploaded_file, is functioning correctly. However, the second unlink function in the moveFTP() method after ftp_put and ftp_close is not ...

Adjusting the color of text based on the fulfillment of a condition

Is there a way to change the text color of a variable based on its value in PHP? For example, if the $status is set to admin, can we display it in red when echoed out using <h3>Status: <?php echo $status; ?></h3>? I'm not quite sure ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

Converting date and time to Epoch in PHP

I am currently working with a substantial list of dates and times, here is a preview... 11/22/2018 01:16:14 AM 11/23/2018 10:59:39 PM My understanding is that the dates follow the format 'm/d/Y h:i:s A', and I am in search of the most efficient ...

Top method for generating a random word for a captcha program using PHP

Currently, I am in the process of developing a fresh captcha script which is nearing completion. However, one thing that remains unresolved is incorporating a list of words into the image text. For instance, I have around 300 five-letter words that I wish ...

"Effortlessly integrate Symfony3 with Select2 to create a dynamic tags

I am in the process of setting up a form to register food products in my database. Along with each product, I also want to include a list of ingredients found on the product packaging. For these two entities, I have created the following classes: Ingredi ...

utilizing switch case to handle login and registration of new users in a PHP application

I attempted to implement a switch case with login and new user submit button functionality, but I am only seeing the default case option with its corresponding values. Below is the code snippet: <?php switch ($_POST['submit']) { ...

Refresh MySQL database using AJAX

In my form, there are both a submit button and a close button. When a user enters information and clicks the submit button, an answer is posted and saved in the database. If the user chooses to click the close button instead, the entry in the database will ...

Conceal the ancestor if the descendant four generations down is vacant

Hey there, I've been working with Beaver Builder on a website and integrating ACF to include a video module. However, not every page will necessarily have a video, and when it's not added, the div.fl-row still appears. I tried using a function to ...

Exploding and imploding multiple images in Laravel

I am currently working on a project that involves multiple images. Everything is functioning properly as of now. However, I would like to display just one image in products.blade.php, while displaying all images in productshow.blade.php. Here is an overvie ...

Execute a SQL query every half minute to retrieve a count, and store the results in a designated file

As I work on creating a website, I have incorporated a database that allows users to input data in the form of votes. To enhance user experience, I want to display a counter in the header showing the total number of votes cast so far. However, considering ...

Rule for identification in the .htaccess file

Is it possible to globally rewrite URLs with GET variables instead of targeting specific files? Transforming http://example.com/{something}?id=1 To: http://example.com/{something}/id/1 Or even without using the word id: http://example.com/{something} ...

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...

Looking to implement C++ constructor and destructor on the stack within PHP

When working with a function that has multiple exit points, I need to lock tables upon entry and automatically unlock them on exit no matter how the function ends (exception, return, etc). In C++, I would achieve this by creating a class with table lockin ...

"Enhance your website's user experience by implementing drag-and-drop functionality

Product Name Barcode Quantity 2*WHITER RIN (200 GM) 8901030295232 null 2*WHITER RIN JASMINE FRESH(500 GM) 8901030295201 null 2*WHITER RIN (200 GM) 890103029 ...

Building a website on Netlify using CURL in PHP

Currently, I am utilizing curl commands to fetch information about the sites on my netlify account. However, as per the API documentation, I should also be able to create a site using POST method. Unfortunately, I am encountering an issue where after runni ...

Using PhpStorm to update a URL after modifying the DocumentRoot

Currently, I am working on a Laravel 8 project with my DocumentRoot set to the public folder. When I enter http://localhost/ in my browser, it displays the contents of the public folder due to my webserver setup. In PhpStorm, I added this folder as a Res ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

What is the best way to apply a CSS class to newly added records within an HTML table that are being fetched from a MySQL database?

The title does not provide clear instructions. If more details are needed, the code below displays data from a MySQL database table on an HTML page: <?php $db_host = 'localhost'; $db_name = 'DB'; ...