[英]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'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.