[Solved] Can I improve my PDO method (just started)


catch(PDOException $e) {
    echo '<p class="error">Database query error!</p>';
}

I would use the opportunity to log which database query error occurred.

See example here: http://php.net/manual/en/pdostatement.errorinfo.php

Also if you catch an error, you should probably return from the function or the script.

if ($STH) {  // does this really need an if clause for it self?

If $STH isn’t valid, then it should have generated an exception and been caught previously. And if you had returned from the function in that catch block, then you wouldn’t get to this point in the code, so there’s no need to test $STH for being non-null again. Just start fetching from it.

    $row = $STH->fetch();

    if (!empty($row)) {  // was there found a row with content?

I would write it this way:

$found_one = false;
while ($row = $STH->fetch()) {
    $found_one = true;
    . . . do other stuff with data . . .
}
if (!$found_one) { 
    echo "Sorry! Nothing found. Here's some default info:";
    . . . output default info here . . .
}

No need to test if it’s empty, because if it were, the loop would exit.

7

solved Can I improve my PDO method (just started)