PHP MySQL Connection Close

To close a mysql connection we can use mysql_close() function. It can takes a optional parameter as link and closes it. If no link identifier is specified then last opened connection is closed. It is not necessary to use mysql_close() function as all connections are closed at the end of the script execution. Here is the function
mysql_close()
Note that mysql_close() will not close persistent connection created by using mysql_pconnect()

Example of MySQL connection, query execution and closing connection

The sequence is to first connect to MySQL database , then mange the database and finally close the connection.
<?Php
$servername='localhost'; 
// username and password to log onto db server 
$dbuser='root'; 
$dbpassword='test'; 
// name of database 
$dbname='sql_tutorial'; 

connecttodb($servername,$dbname,$dbuser,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
/// Connection is over ///////

/// Query details ///// 
$query = mysql_query("SELECT * FROM student"); 
$number=mysql_num_rows($query); 
echo "Total records in Student table= ". $number;

///// Let us close connection  //////
mysql_close($link);
?>
PHP MySQL functions Connecting to MySQL database

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer