Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL PDO - What should be inside the try { block }?

Tags:

php

mysql

pdo

So I'm working on learning PDO, and making the transfer from the standard PHP MySQL functions. However, I have a question. Regarding the try {} blocks, what exactly should be in them, and what should go outside it?

Should everything that uses $sth-> ... be inside try {}? Should it just be from when the statement is first prepared all the way to when it is executed? Even less than that?

Any help would be greatly appreciated. :)

Here is an example method I have in a class. Is it organized properly? Notice how I put everything inside try {}. Is that wrong? It feels incorrect to me, but I'm not sure how I should change it.

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);
    }
}
like image 950
Nathanael Avatar asked Jun 14 '12 19:06

Nathanael


1 Answers

The try catch should be outside the function.

<?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);
}

Don't handle exceptions inside of the methods. You try the method and catch the resulting exception if it happens.

like image 106
Madara's Ghost Avatar answered Sep 21 '22 13:09

Madara's Ghost