因此,大多数基本的 php/mysql 示例都显示出类似这样的内容(取自 W3 Schools 作为外行示例):
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
使用外部连接文件时,关闭连接的正确方法是什么(如果需要)。
例如。我们将上面的内容分成一个 connection.php 文件,其中包含
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
然后有一个 Query.php 文件,其中包含:
<?php
require('connection.php');
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
是否有必要关闭连接。是否应该mysqli_close($con);
在 query.php 文件的末尾有一个,或者它是否在 connection.php 文件的末尾,并且有某种方式来链接 query.php 文件将在连接关闭之前运行?
和/或是否需要关闭连接?脚本完成后它会自动关闭吗?