10

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);
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Nathanael
  • 6,893
  • 5
  • 33
  • 54

1 Answers1

8

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.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • Hmm, okay, that makes sense in this instance. What about when it's not inside a function? In another script I have, I have several nested loops and conditionals, et cetera, and it's several hundred lines long. In that situation, would I wrap the entire code block in a `try {}`? In other words, should EVERYTHING be inside the `try {}` always--with "everything" being anything that makes used of `$dbh` or `$sth`? – Nathanael Jun 14 '12 at 19:23
  • What if the method throws something other than a `PDOException`? – Mike Jun 14 '12 at 19:24
  • @Mike: You catch an `Exception` as well, which is the generic type and will catch all exceptions type. You can catch multiple exceptions. – Madara's Ghost Jun 14 '12 at 19:24
  • @NathanaelShermett: Yes. But in general, all of your business logic, which is most likely to throw exceptions, should be inside of classes and methods. In the off shot where you need to execute code outside of a function and throw exceptions, you should wrap the try/catch over everything. – Madara's Ghost Jun 14 '12 at 19:27
  • isn't this *exactly* the same as having no try catch block with proper error modes? try catch should be used to infer different behaviour from a script, not just report errors that would be reported anyway - http://stackoverflow.com/questions/23571128/pdo-fatal-error-reveals-username-and-password/23573888#23573888 – Félix Adriyel Gagnon-Grenier May 21 '14 at 19:10
  • @FélixGagnon-Grenier: Not really. It's true that you don't always want to report an error, but usually, you still don't know what to do with the problem inside the function calling PDO. Do you want to log it? Exit? Try and connect again? I don't know. Which is why I leave the *caller*, as in, the method that invoked the one acting with PDO, to do the error handling, or let it propagate higher if needed. – Madara's Ghost May 21 '14 at 19:14