【发布时间】:2020-04-20 13:15:25
【问题描述】:
我知道结束准备好的语句是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
还是在我使用完准备好的语句后立即关闭它们以避免任何类型的错误更好?
【问题讨论】:
-
PHP 有一个垃圾回收器,它将在脚本结束时被释放。但是当你不再需要它时,你应该关闭它。
-
你应该使用 exit();在每次标头调用之后,停止脚本的处理。
-
@JayBlanchard 我知道,这只是一个Minimal Reproducible Example
-
@MarkusZeller 所以我应该选择第二个选项吗? (每次重定向前关闭)
-
我肯定更喜欢那个。但如前所述,PHP 将在退出时自行清理。
标签: php mysqli header prepared-statement