-3

Description :

Lets say I am fetching some data from a php page like below

<?php  

include 'connect_to_database.php';
while ($data = mysqli_fetch_array(mysqli_query($con,"select * from myTable"),MYSQLI_BOTH))
{
   echo $data['product'];
}

mysqli_close($con);

?>

now what is mysql_close($con); doing there exactly is it closing the connection for this page only or as a whole disconnecting the website from database which has to be connected again to work .. further more I read writing exit at the end of php is a very good practice as if we dont do this then the page keeps executing in the server thus occupies space ...

Can anyone explain ?

Rks Rock
  • 79
  • 4
  • 13
  • 1
    As many request can be sent to the server, changes are the server can run out of available connections when the connections are not closed and stay open. – Barry Oct 25 '14 at 08:18
  • 1
    Database connections automatically terminate when the page execution is finished. Still, it's a good habit to free up resources when you're done with them. – Dave Chen Oct 25 '14 at 08:18

2 Answers2

1

It closes the connection referenced by the variable $con. It possible to have more than one connection and then it just closes that one you've specified in the first parameter of mysqli_close().

algorhythm
  • 8,530
  • 3
  • 35
  • 47
1

mysqli_close() closes the connection to the database for that specific page ONLY, there is nothing such as disconnecting the website from database which has to be connected again to work, a new connection is started on each page and the connection is automatically closed once the execution ends. mysqli_close() will close it before the execution ends, so to demonstrate this

<?php
// connection starts here
mysqli_query($link, "whatever stuff you need to do");
?>
// The connection is closed here 

In another example of how mysqli_close is used

<?php
// connection starts here
mysqli_query($link, "whatever stuff you need to do");
mysqli_close($link); // the connection is closed here 
// do whatever more stuff you have to do that are unrelated to the database
?>

As to exit, it's only use is breaking out of the code, there's no use in placing it at the end of the code
Using it this way below would be useless:

<?php
echo 'Hi';
echo 'Bye';
exit(); // this is useless because all code has been executed already 
?>

The example below, is useful:

<?php
echo 'Hi';
exit(); // this is useful as it stops the execution of whatever code is below it. 
echo 'Bye';
?>
Ali
  • 3,479
  • 4
  • 16
  • 31