Netbeans 不断向我发出“嵌套块太多”的烦人通知,并建议我引入新功能,但以下做法真的很糟糕吗?
$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?
}
Run Code Online (Sandbox Code Playgroud)
所以看来每次我编写 SQL 查询时我都已经达到了 Netbeans 推荐的嵌套块限制 - 我可以安全地使这个更灵活吗?我知道这只是一个编码“提示”,但我想检查一下我没有做任何非常愚蠢的事情:)
好吧,这还不错,但是,根据您的喜好,您可以首先处理“错误”情况,避免嵌套if语句,如下所示:
$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);
}
Run Code Online (Sandbox Code Playgroud)
如果有很多事情可能会出错,或者有很多方法可以处理一种特定情况,那么这将是一种更好的方法,而不是造成if() { if() { if() { if() { ... }}}}混乱。