MySQL PDO - try {block}中应包含哪些内容?

Nat*_*ael 10 php mysql pdo

所以我正在学习PDO,并从标准的PHP MySQL函数转移.但是,我有一个问题.关于try {}块,究竟应该在哪些块中,以及应该在它之外的内容?

应该使用的一切都$sth-> ...在里面try {}吗?它应该是从语句第一次准备到执行的时间吗?甚至不到那个?

任何帮助将不胜感激.:)

这是我在课堂上的一个示例方法.组织得当吗?注意我是如何把一切try {}.那是错的吗?对我来说感觉不对,但我不确定如何改变它.

protected function authorized()
{
    try
    {
        // Attempt to grab the user from the database.
        $sth = $dbh->prepare("
            SELECT COUNT(*) AS num_rows
            FROM users
            WHERE user_id = :user_id
            ");

        $sth->bindParam(':user_id', $this->user_id);
        $sth->execute();

        // Check if user exists in database.
        if ($sth->fetch()->num_rows > 0)
        {
            // User exists in database, and is therefore valid.
            return TRUE;
        }
        else
        {
            // User does not exist in database, and is therefore invalid.
            return FALSE;
        }
    }
    catch (PDOException $e)
    {
        pdo_error($e);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 8

try catch应该在函数之外.

<?php

protected function authorized() {
    // Attempt to grab the user from the database.
    $sth = $dbh->prepare("
            SELECT COUNT(*) AS num_rows
            FROM users
            WHERE user_id = :user_id
            ");

    $sth->bindParam(':user_id', $this->user_id);
    $sth->execute();

    // Check if user exists in database.
    if ($sth->fetch()->num_rows > 0) {
        // User exists in database, and is therefore valid.
        return TRUE;
    }
    else {
        // User does not exist in database, and is therefore invalid.
        return FALSE;
    }
}

...

try {
    authorized()
}
catch (PDOException $e) {
    pdo_error($e);
}
Run Code Online (Sandbox Code Playgroud)

不要处理方法内部的异常.您尝试方法并在发生时捕获生成的异常.