如何优化这两条线


How do I optimize these two lines?

所以,我有这两行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'];

非常感谢!

您的第二个代码段自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'];
}