Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 其中';关闭数据库连接的最佳位置是哪里?_Php_Mysql - Fatal编程技术网

Php 其中';关闭数据库连接的最佳位置是哪里?

Php 其中';关闭数据库连接的最佳位置是哪里?,php,mysql,Php,Mysql,在这段代码中,我认为最好在if和else之后关闭,但似乎关闭了两次 <?php $member_id = ""; require("connect.php"); if (isset($_POST['member_id']))$member_id = fix_string($_POST['member_id']); $sql=("DELETE FROM members WHERE member_id = '$member_id'"); $res = mysqli_query($con,

在这段代码中,我认为最好在if和else之后关闭,但似乎关闭了两次

<?php 
$member_id = "";
require("connect.php");
if (isset($_POST['member_id']))$member_id = fix_string($_POST['member_id']);

$sql=("DELETE FROM members WHERE member_id = '$member_id'");
$res = mysqli_query($con, $sql);

if (mysqli_affected_rows($con) == 1) {
    echo "member with ID of ".$member_id." has been removed from members table";
} else {
    echo "member was not deleted";
}

function fix_string($string) {
    if (get_magic_quotes_gpc()) $string = stripslashes($string);
    return htmlentities ($string);
}
?>

通常的做法是在开始时打开db连接,然后在结束时关闭一次连接。你不需要在代码的中间进行。

关闭数据库连接并不是绝对必要的,如的PHP手册页面所示,但许多人认为关闭数据库连接是一种很好的做法

这是一个罕见的例外。如果您的程序将在几分钟内执行一些繁重的处理,您可能希望在此之前关闭db连接。如果在处理后再次需要,请再次打开db连接。原因是MySQL连接最终会超时,然后可能会导致程序中出现更多问题。

通常不需要使用MySQL\u close(),因为非持久打开的链接会在脚本执行结束时自动关闭


退出php手册。

只需在文件末尾关闭它。