php – 不应该准备好更快的语句吗?

前端之家收集整理的这篇文章主要介绍了php – 不应该准备好更快的语句吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
$s = explode (" ",microtime());
$s = $s[0]+$s[1];
$con = MysqLi_connect ('localhost','test','pass','db') or die('Err');

for ($i=0; $i<1000; $i++) {

  $stmt = $con -> prepare( " SELECT MAX(id) AS max_id,MIN(id) AS min_id FROM tb ");
  $stmt -> execute();
  $stmt->bind_result($M,$m);
  $stmt->free_result();
  $rand = mt_rand( $m,$M ).'<br/>';

  $res = $con -> prepare( " SELECT * FROM tb WHERE id >= ? LIMIT 0,1 ");
  $res -> bind_param("s",$rand);
  $res -> execute();
  $res->free_result();
}

$e = explode (" ",microtime());
$e = $e[0]+$e[1];
echo  number_format($e-$s,4,'.','');

// and:

$link = MysqL_connect ("localhost","test","pass") or die ();
MysqL_select_db ("db") or die ("Unable to select database".MysqL_error());

for ($i=0; $i<1000; $i++) {
  $range_result = MysqL_query( " SELECT MAX(`id`) AS max_id,MIN(`id`) AS min_id FROM tb ");
  $range_row = MysqL_fetch_object( $range_result ); 
  $random = mt_rand( $range_row->min_id,$range_row->max_id );
  $result = MysqL_query( " SELECT * FROM tb WHERE id >= $random LIMIT 0,1 ");
}

准备好的陈述更加安全
但是每一个地方都说它们要快得多
但在我对上述代码的测试中,我有:
– 准备好的陈述2.45秒
– secon示例5.05秒

你觉得我做错了什么?
我应该使用第二种解决方案,还是应该尝试优化准备工作?

你做错了的是你准备了一千次这个陈述并且只运行一次准备好的陈述.你应该准备一次,并运行一千次.

猜你在找的PHP相关文章