When do I need to close mysqli (database) connection?
P粉311464935
2023-08-24 23:50:20
<p>Currently, I have a connect.php file like </p>
<pre class="brush:php;toolbar:false;">$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);
}</pre>
<p>In all other PHP files that use MySQL queries, I use "include 'connect.php';"</p>
<p>For instances on W3Schools, they create a new connection for each query and then close it after use. See here: w3schools.com: I'm not sure if they're doing this just for demonstration purposes or if it's a best practice. </p>
<p>Do I have to close the connection after each selection and make a new connection for the next query? If not, when do I finally have to close the connection? at the end of the PHP file containing all queries? </p>
When you are finished using the connection on this page, please close the connection. For example, if you have a blog, the button for publishing the blog will start the code that opens the connection, does something with the connection (such as adding it to the database or displaying it on the page), and then it closes the connection , so that it doesn't stay open longer than it needs to. However, when you click the button again, it will start the process over, using the resource only when needed.
Quoted from the php.net website.
Source: http://php.net/manual/en/mysqli.close .php