关闭准备好的陈述 [英] Closing prepared statements

查看:87
本文介绍了关闭准备好的陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,关闭准备好的语句是建议要做的事情.

I know that closing prepared statements is a suggested thing to do.

但是我有一个 PHP 脚本,如下所示:

But I have a PHP script like this:

$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");

如果一切正常,该语句将被关闭,但是在执行过程中出现故障时,该语句不会被关闭.

The statement gets closed if everything is ok, but when something fails during the execution it doesn't get closed.

我应该写

else {
    $stmt->close();
    header("Location: .?error=unknown");
}

else {
    $stmt->close();
    header("Location: .?error=conn");
}

或者,由于发生了错误,我不用担心关闭语句吗?

or, since an error occurred, I shouldn't worry about closing the statement?

或者我什至可以写:

$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

还是最好在我使用完准备好的语句后关闭准备好的语句,以避免出现任何错误?

or is it better to close the prepared statements right after I have finished using them to avoid any sort of bugs?

推荐答案

您的代码的问题不是使用close(),而是错误报告(未启用).您必须启用 mysqli错误报告,然后才能简化代码.

The problem with your code is not the use of close(), but the error reporting, which is not enabled. You must enable mysqli error reporting and then you can simplify your code.

理想情况下,您的数据库操作应该包装在一个函数或方法中,这样您就不必担心关闭任何东西.它将自动为您关闭.

Your DB operations should ideally be wrapped in a function or a method and then you do not need to worry about closing anything. It will be closed for you automatically.

$sql = "SELECT * FROM `mytable` WHERE ...";
$stmt = $dbh->prepare($sql);
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

如果要将其包装在函数中,则无需close().

If you were to wrap it in a function, then there is no need for close().

function getResults(\mysqli $dbh, string $sql, string $types, array $params): array {
    $stmt = $dbh->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

然后,如果您有异常,则应创建一个通用错误处理程序,该错误处理程序将在发生错误时通过生成HTTP 500响应代码将用户重定向到500页,并将记录所有异常详细信息放入服务器上的文件.

Then if you have an exception you should create a generic error handler, which will redirect the user to 500 page by generating HTTP 500 response code when an error happens, and will log all the exception details into a file on the server.

这篇关于关闭准备好的陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆