Answer the question
In order to leave comments, you need to log in
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;
}
}
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();
}
$db = DB::init()
$q =$db->prepare(DB::SQL_ADD_PROF);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question