我知道关闭准备好的语句是a suggested thing to do。
但是我有一个像这样的PHP脚本:
$sql = "SELECT * FROM `mytable` WHERE ...";
$stmt = $dbh->stmt_init();
if($stmt->prepare($sql))
{
$stmt->bind_param("s", $user);
if($stmt->execute())
{
$result = $stmt->get_result();
$stmt->close();
} else
header("Location: .?error=unknown");
} else
header("Location: .?error=conn");
如果一切正常,该语句将关闭,但是在执行过程中发生故障时,它不会关闭。
我应该写
else {
$stmt->close();
header("Location: .?error=unknown");
}
和
else {
$stmt->close();
header("Location: .?error=conn");
}
或者,由于发生了错误,我不应该担心关闭语句吗?
或者我什至可以写:
$sql = "SELECT * FROM `mytable` WHERE ...";
$stmt = $dbh->stmt_init();
if($stmt->prepare($sql))
{
$stmt->bind_param("s", $user);
if($stmt->execute())
{
$result = $stmt->get_result();
} else
header("Location: .?error=unknown");
} else
header("Location: .?error=conn");
/*some other code*/
$stmt->close; //close every statement at the very end of the script
或者在我完成使用准备好的语句以避免任何类型的错误之后立即关闭准备好的语句?
如果要确保可以执行以下操作:
$sql = "SELECT * FROM `mytable` WHERE ...";
$stmt = $dbh->stmt_init();
$header_string = '';
if($stmt->prepare($sql))
{
$stmt->bind_param("s", $user);
if($stmt->execute())
{
$result = $stmt->get_result();
} else
$header_string = 'Location: .?error=unknown';
} else
$header_string = 'Location: .?error=conn';
/*some other code*/
$stmt->close; //close every statement at the very end of the script
header($header_string);