R
R
rvller2013-01-06 09:13:43
PHP
rvller, 2013-01-06 09:13:43

Lost connection to MySQL server during query

PHP Guru, tell me why.

There is a class that has a static method for connecting to the database:

class DB
{
    static function init()
    {
        // blah-blah-blah

        $db = new mysqli($host, $user, $pass, $bd_name);
        if (mysqli_connect_errno()) {
            echo("Подключение к серверу MySQL невозможно. Код ошибки: ".mysqli_connect_error()."\n");
            exit;
        }
        return $db;
    }
}


And there is a method that uses it:

function add_prof() {
    
    $name = trim($_POST['name']);
    
    $q = DB::init()->prepare(DB::SQL_ADD_PROF);
    $q->bind_param('s', $name);

    $q->execute();
    echo "err".$q->error;
    $q->close();

}


With this entry: $q = DB::init()->prepare(DB::SQL_ADD_PROF);
On the line $q->bind_param('s', $name); “Lost connection to MySQL server during query” crashes.

But if you write like this:
$db = DB::init()
$q =$db->prepare(DB::SQL_ADD_PROF);


That all works.
PHP 5.3.3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cutwater, 2013-01-06
@rvller

The fact is that the local variable $db, which you return from the function after calling $prepare, is destroyed, and the connection to MySQL is closed accordingly.
In the second example, you extend the lifetime by assigning the result to DB::init and thus you keep the connection as long as $db is alive.
This is a "simple explanation", for a deeper understanding read about refcounting, garbage collection mechanisms in PHP
php.net/manual/en/features.gc.refcounting-basics.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question