So, I’ve been learning PDO. So far, I am not at all impressed, honestly, due to the large amount of code needed to do small tasks. However, I am willing to convert nonetheless if I can get my code to be efficient and reusable.
My question is this: can I make this code any more efficient? By efficient, I mean both A) take up less lines, and B) run faster. I am worried that I am going about this all wrong. However, due to the lack of a num_rows() function, I can’t think of a better way.
try
{
$sth = $dbh->prepare("SELECT * FROM table_name");
$sth->execute();
if (count($result = $sth->fetchAll()))
{
foreach ($result as $value)
{
// Rows returned! Loop through them.
}
}
else
{
// No rows returned!
}
}
catch (PDOException $e)
{
// Exception!
}
Is this written properly?
As far as my research has shown, no. There is no way to rewrite this code more concisely or logically–the way it stands is entirely optimized. 🙂 It’s easy to use, so that’s definitely not a bad thing!