Encountered a "MySQL server has disconnected" error while preparing a mysqli statement

Struggling with the transition from Procedural to Object Oriented programming, so please excuse any untidiness or errors in my code. Here is an example where I am passing posts through jQuery to a class for updating a record when a user checks a checkbox:

This is the database connection:

class db {
    
    private $host ;      
    private $username;
    private $password;
    private $dbname;
                
    protected function conn()
    {
        $this->host = "localhost";
        $this->username = "root";
        $this->password = "";
        $this->dbname = "mytest";
    
        $db = new mysqli($this->host, $this->username,  $this->password, $this->dbname);
        
        if($db->connect_errno > 0){
                die('Unable to connect to database [' . $db->connect_error . ']');
        }
        
        return $db;
    
    }
            
}

This is the update class:

class updOrders extends db {

public $pid;
public $proc;

public function __construct()
{
$this->pid = isset($_POST['pid']) ? $_POST['pid'] : 0;
$this->proc = isset($_POST['proc']) ? $_POST['proc'] : 1;
   
// $stmt = $this->conn()->query("UPDATE tblorderhdr SET completed = ".$this->proc." WHERE orderid = ".$this->pid);

$stmt = $this->conn()->prepare("UPDATE tblorderhdr SET completed = ? WHERE orderid = ?");
$stmt->bind_param('ii', $this->proc, $this->pid);

 $stmt->execute();

if($stmt->error)
    {
        $err = $stmt->error ;
    } else {
        $err = 'ok';
    }
    
/* close statement */
$stmt->close();

 echo json_encode($err);   

}
    
}

$test = new  updOrders;

When I comment out the prepare statement and run the query directly (commented out) it updates successfully. However, when I try to run it as a prepared statement, it returns an error "MySQL server has gone away".

Answer №1

Upon reviewing your code, I came across the following:

$stmt = $this->conn()->prepare("UPDATE tblorderhdr SET completed = ? WHERE orderid = ?");

I implemented something similar in my code. However, I noticed that you separated the connection from the prepare function.

$db = $this->conn();

$stmt = $db->prepare("UPDATE tblorderhdr SET completed = ? WHERE orderid = ?");

Although I'm not sure why, this approach seems to be working fine now.

Answer №2

It seems that the issue is related to the database connection. Check out the updated code snippet below:

$db = $this->connect();

$stmt = $db->prepare("UPDATE tblorderhdr SET completed = ? WHERE orderid = ?");
$stmt->bind_param('ii', $this->process, $this->product_id);

$stmt->execute();

Answer №3

Every time you call $this->conn(), a new connection object of the class mysqli is created. Once there are no more variables pointing to this object, PHP will trigger its destructor which will close the connection. If you do not store the return value of this method in a variable, the object will lose all references and the connection will be closed.

To solve this issue, it's recommended to save the object and reuse it instead of reconnecting each time.

$conn = $this->conn();
$stmt = $conn->prepare("UPDATE tblorderhdr SET completed = ? WHERE orderid = ?");

In addition, creating a class like your current one, db, seems unnecessary as it doesn't provide any additional functionality to mysqli. Storing credentials in properties is also redundant. You can easily replace the entire class with the following code:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'password', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset

After making these changes, your classes should expect the mysqli object as a dependency.

class updOrders {

public $pid;
public $proc;

public function __construct(mysqli $conn) {
}

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

Generating a dropdown menu populated by a linked table in Yii framework

I am currently working with two tables: product and product_type which are connected to the models Product and Product_type respectively: product : product_id, product_type_id, name, etc... product_type : product_type_id, name, desc, etc... Both tables a ...

Having an issue with saving multiple checkbox values in a CSV file using PHP. Unfortunately, only one value seems to be getting

I have encountered an issue with exporting data from a form to a csv file. While the radio buttons are working perfectly fine, I am facing problems in exporting the value of textarea and all selected checkboxes. Only one value is being exported, and I can& ...

Utilizing CURL for PHP to extract information from any webpage

Can a PHP function be created to generate an HTML string of any link like a browser does? For example, links such as "", "", "mywebsite.com", "somesite.com/.page/nn/?s=b#85452", "lichess.org" What I have attempted: $curl = curl_init(); curl_setopt($curl, ...

Switching to an Apache server from a node.js server

I have been working with react-webpack and running my project on node.js. However, I now need to incorporate some PHP files into the project due to new requirements. I am unsure of how to add PHP files to my project and transition from node.js to Xampp in ...

Find a solution for displaying custom product badges

Having some issues with a custom product badge on my website. I tried adding a new badge (besides "Sale"), but it seems to be displaying in the wrong position. The badge should display as "Choice" on the featured products, so I added this code to the chil ...

Using SQL aliases in PHP

Could someone please assist me in locating the error in my SQL statement? I am encountering an issue with my query and believe it may be related to the use of aliases while trying to display the names of two football teams in a fixture list. This is how my ...

The specified route [Controller@method] does not exist

I'm currently working on creating a form that will interact with a controller method to insert new data into the database. I am using Laravel Version 4.1 app/views/projects.blade.php <tr> {{Form::open(array('action' => 'Pr ...

Guidelines for utilizing the DISTINCT keyword in MySQL server to retrieve specific data

Consider this given value: $weight = 50 In my database, I possess the names of four individuals. Their respective weights are 40, 50, 35, and 54. What I desire is to obtain the names of those individuals whose weight falls within the range of $weight+10 a ...

A guide to combining and categorizing values with MySQL

I'm seeking advice on how to sum and group values in MySQL. It seems like a straightforward task, but I've encountered a unique situation. My table records the number of cigarettes smoked by users each day, and I'm attempting to calculate t ...

Upgrading email functionality: Combining PHP mail() with AJAX

My issue revolves around using the mail() function. When AJAX code is present, the email gets sent but without any message (the subject is intact though). However, when I remove the AJAX code, the email goes through without any problems. I'm not well ...

Pass arguments in an ajax request when making a request with jQuery datatables

My goal is to populate a jQuery datatable using ajax and pass parameters to the function retrieving data from the database. This is what I want to achieve: $('#datatables').dataTable( { "bProcessing": true, "bServerSide": true, "sAj ...

Arrange charges by title in WooCommerce orders and email alerts

Is there a way to sort fees by name instead of the default sorting by price in WooCommerce orders? I was able to successfully sort fees by name on the cart and checkout pages using the code provided in the answer located at Reordering multiple fees differ ...

Unable to retrieve session data through Laravel 5.4 AJAX request

When using Laravel 5.1, this code snippet works perfectly on an ajax call: $conn = Session::get('conn') or abort(500, 'No conn detected') The variable is properly set and if the session key is not found, the error 500 is triggered. H ...

There seems to be a problem communicating securely with the server due to an SSL handshake failure with error code 14077410

$ch = curl_init(); $clientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; $secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token"); curl_set ...

What are the steps to execute a php script on fpm using the cli/php?

I recently came across DeferredEventJavaWorker and I'm curious if it's possible to run a php script directly on fpm using cli/php. In the Java and Ruby worker implementations, fpm is called with parameters. It seems like this should also be achi ...

PHP function preg_match has a limit on the maximum number of non-greedy matches allowed

Is there a maximum number of times the non-greedy .*? match can be used in a regular expression in PHP? I have a haystack that is approximately 200k characters long and I need to determine if 75 numbers are in the correct order. While I am aware there may ...

Is it possible to utilize a JavaScript variable in this particular scenario and if so, what is the

let myVariable = <?php echo json_encode($a[i want to insert the JS variable here]); ?>; Your prompt response would be highly valued. Many thanks in advance. ...

Create dynamic combo boxes using jQuery

My goal is to display a text field on the page if a user has only one credit card number in the database. However, if the user has multiple credit card numbers stored, I want to display all of them in a combo box. Below is the ajax response that I am rece ...

Unfortunately, I am currently unable to showcase the specifics of the items on my website

I am trying to create a functionality where clicking on a product enlarges the image and shows the details of the product as well. While I have successfully implemented the image enlargement, I am facing challenges in displaying the product details. Below ...

Assistance in utilizing CodeIgniter and MYSQL to execute Select and Join operations across various tables

I am currently working on a query implementation in Codeigniter that will enable users to retrieve records they have previously submitted to my database. Here is the schema I am using: https://i.stack.imgur.com/zSHSQ.png I am facing challenges in unders ...