如何优化这两条线?

时间:2013-08-13 05:04:35

标签: php optimization variable-declaration

所以,我有这两行PHP。

$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db));
$total_row_count = $total_row_count['count'];`

有没有办法更改$ total_row_count的第一个声明,所以第二行不是必需的?

达到此效果(我知道这不是功能代码)。

$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db))['count'];

非常感谢!

1 个答案:

答案 0 :(得分:0)

自PHP 5.4以来,您的第二个片段功能完善 。它被称为直接阵列解除引用。

但是,你永远不应该做mysql_fetch_assoc(mysql_query(...))mysql_query调用可能会失败并返回false,这会将丑陋的错误传播到mysql_fetch_assoc您需要处理错误!

$result = mysql_query(...);
if (!$result) {
    die(mysql_error());
    // or
    return false;
    // or
    throw new Exception(mysql_error());
    // or whatever other error handling strategy you have
}

$row = mysql_fetch_assoc($result);
$count = $row['count'];

如果这个代码太多而无法经常重复,请将其包装在函数中。

function getCount() {
    $result = mysql_query(...);
    ...
    return $row['count'];
}
相关问题