Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

php - When do I have to close mysqli (Database) connection?

For now, I have one connect.php file e.g.

$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";

$con = new mysqli(
    $mysql_host,
    $mysql_user,
    $mysql_password,
    $mysql_database
);

// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

In every other PHP file that uses MySQL queries, I use "include 'connect.php';"

For Instance on W3Schools, they create for every query a new connection and then close it after use. See here: w3schools.com: I'm not sure if they do it just for showing purpose, or if it is best practice to do it this way.

Do I have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the PHP File with all the queries?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A quote from the php.net site.

Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.

Source: http://php.net/manual/en/mysqli.close.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...