Php 如何优化这两条线?
我有两行PHPPhp 如何优化这两条线?,php,optimization,variable-declaration,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\u row\u count的第一个声明,这样就不需要第二行了 类似的东西(我知道这不是函数代码) 非常感谢 第二个代码段自PHP5.4以
$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\u row\u count的第一个声明,这样就不需要第二行了
类似的东西(我知道这不是函数代码)
非常感谢 第二个代码段自PHP5.4以来功能完善。这叫做直接数组解引用 但是,您永远不应该执行
mysql\u fetch\u assoc(mysql\u query(…)
。mysql\u查询
调用可能会失败并返回false
,这会将难看的错误传播到mysql\u fetch\u 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'];
}
我确实找到了这个,有没有更好的办法$total_row_count=array_shift(mysql_fetch_assoc(mysql_查询(sprintf('SELECT count(*)作为来自%s'的计数,$table_name,$db));实际上,您应该使用更多的代码。您需要在查询之后立即进行错误处理。如果你不喜欢到处重复的话,就把整个过程包装在一个函数中。
function getCount() {
$result = mysql_query(...);
...
return $row['count'];
}