wall-nut
wall-nut

Reputation: 403

PHP PDO using try

For best practices should I be putting the fetch command portion inside of the try statement or is the prepare and execute sufficient?

$sql    = "SELECT * FROM links WHERE device = 'mobile' AND category = ? ORDER BY category asc, link_id asc";

try{
    $sth = $dbh->prepare($sql);
    $sth->bindValue(1, $cat, PDO::PARAM_STR);
    $sth->execute();
} 
catch(\PDOException $ex){
    print($ex->getMessage()); 
}

if($sth->rowCount()) {        
    print("<a data-rel=\"dialog\" data-transition=\"pop\" href=\"index.php?action=addnew&cat=$cat\">Add New Menu Item</a><br/><br/>");
    print("<ul data-role=\"listview\" data-filter=\"true\">");
    while($row = $sth->fetch(PDO::FETCH_BOTH)) {    
        print("<li>");
        print("<a data-transition='fade' href='$row[$COL_HREF]'>$row[$COL_LINK_NAME]<br/></a>");
        print("</li>\n");
    }
    print("</ul>");
}

Upvotes: 1

Views: 75

Answers (1)

bcmcfc
bcmcfc

Reputation: 26795

Inside the try with the rest of the code.

If the code in your try produces an Exception, you're printing out the exception message but are then continuing to check the rowCount(), which is dependent on $sth being successfully set and executed.

Upvotes: 1

Related Questions