如果你使用mysqli扩展而不是mysql,你可以使用fetch_all(),这比在一个循环中填充数组要快。所以,你的函数只需要返回fetch_all的结果()
return $result->fetch_all(MYSQLI_ASSOC);
脚本
<?php
ob_start();
try
{
$db = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);
if ($db->connect_errno)
throw new exception(sprintf("Could not connect: %s", $db->connect_error));
$sqlCmd = "select * from users order by username";
$startTime = microtime(true);
$result = $db->query($sqlCmd);
if(!$result) throw new exception(sprintf("Invalid query : %s", $sqlCmd));
if($result->num_rows <= 0){
echo "no users found !";
}
else{
$users = $result->fetch_all(MYSQLI_ASSOC); //faster
//while($row = $result->fetch_assoc()) $users[] = $row; //slower
echo sprintf("%d users fetched in %s secs<br/>",
count($users), number_format(microtime(true) - $startTime, 6, ".", ""));
foreach($users as $u) echo $u["username"], "<br/>";
}
// $result->close();
}
catch(exception $ex)
{
ob_clean();
echo sprintf("zomg borked - %s", $ex->getMessage());
}
//finally
if(!$db->connect_errno) $db->close();
ob_end_flush();
?>
测试
//fetch_all()
1000 users fetched in 0.001462 secs
5000 users fetched in 0.005493 secs
15000 users fetched in 0.015517 secs
50000 users fetched in 0.051950 secs
100000 users fetched in 0.103647 secs
//fetch_assoc plus loop
1000 users fetched in 0.001945 secs
5000 users fetched in 0.008101 secs
15000 users fetched in 0.023481 secs
50000 users fetched in 0.081441 secs
100000 users fetched in 0.163282 secs
你创建的config.php文件$ CON? – aorcsik 2011-03-19 23:01:12
你能说这个代码有什么错吗? – 2011-03-19 23:08:45
您是否阅读过答案并纠正了其他错误? – markus 2011-03-19 23:34:14