How are database connections opened by mysql_connect() closed?
According to the php documention, "The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier开发者_开发百科 by explicitly calling mysql_close()."
http://php.net/manual/en/function.mysql-connect.php
When are connections opened and closed for this script for 1) when the username is not posted and 2) when the username is posted (please mind form sanitation)?
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (mysql_error());
mysql_select_db("members") or die(mysql_error());
?>
<?php
if (isset ($_POST['username'])){
$username=$_POST['username'];
$sql = mysql_query("INSERT INTO members (username) VALUES('$username'") or die (mysql_error());
}
else{
$username='';
}
?>
<html>
<form action="register.php" method="post" enctype="multipart/form-data">
<input type="text" name="username" size="30" maxlength="400" value="<?php echo htmlentities(stripslashes($username)); ?>" />
</form>
</html>
The connection is opened at the top of the script, regardless of if the form is posted or not, therefore is opened once on each page load. The connection is closed once the final </html>
tag is delivered to the client.
精彩评论