Home  >  Q&A  >  body text

When do I need to close mysqli (database) connection?

<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>
P粉311464935P粉311464935444 days ago505

reply all(2)I'll reply

  • P粉521748211

    P粉5217482112023-08-25 22:19:02

    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.

    reply
    0
  • P粉336536706

    P粉3365367062023-08-25 18:36:36

    Quoted from the php.net website.

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

    reply
    0
  • Cancelreply