Issue
Netbeans keeps giving me annoying notifications for "too many nested blocks" and suggesting I introduce a new function, but is the following really bad practice?
$sql = 'SELECT * FROM table';
$sth = $dbh->prepare($sql);
if ($sth->execute())
{
if ($sth->rowCount())
{
while ($row = $sth->fetch())
{
// Read the database here
}
}
else
{
// Handle no result case here
}
}
else
{
// Catch query failure here - Is this bit necessary if I'm confident the query is OK?
}
So it seems I'm already at Netbeans recommended nested block limit every time I write an SQL query - could I safely make this slicker? I know it is only a coding "hint", but I want to check I'm not doing anything drastically stupid :)
Solution
Well, it's not too bad, but, depending on your preference, you can first handle 'error' cases, avoiding nested if
statements, something like this:
$sql = 'SELECT * FROM table';
$sth = $dbh->prepare($sql);
if (!$sth->execute) {
throw new Exception("Things went bad with the query!");
}
if (!$sth->rowCount()) {
// either throw an exception if you always expect to have results
// or handle the case in whatever way you need
}
while ($row = $sth->fetch()) {
do_something_nice($row);
}
If there are many things that can go wrong, or many ways to handle one specific case, then this would be a bit nicer way instead of having if() { if() { if() { if() { ... }}}}
mess.
Answered By - Oliver Maksimovic