duanli0119 2011-08-10 00:51
浏览 38
已采纳

有效地批量查询数据库

I have a php page that takes 2.8 seconds to render. The page contains a script that reads a txt file via file() line by line (~5000 lines) via a foreach loop. This works perfectly and allows me to wrap each line in a <div>. This all looks something like this.

$text_file = 'path/to/my/text/file.txt';
$lines = file($text_file);
$output = '';
foreach($lines as $line_num => $line){
  $output .= '<div id="'.$line_num.'" class="line">'.htmlspecialchars($line).'</div>'."
";
}
echo $output;

The problem is I need to query if a line number is in the database and if it is give it an extra class highlight. This is what is making the page render so slowly. Each line (~5000) is querying the database within the loop. This looks something like this.

foreach($lines as $line_num => $line){
  // codeigniter is being used here
  $line_exists = $this->line_model->lookup_line($line_num);
  // $line_exists checks the database if the $line_num exists it will return true / false
  if($line_exists){          
    $lines_output .= '<div id="'.$line_num.'" class="line highlight">'.htmlspecialchars($line).'</div>'."
";
  }else{
    $lines_output .= '<div id="'.$line_num.'" class="line">'.htmlspecialchars($line).'</div>'."
";
  }
}

My question is: Is there a more efficient / faster way to do this?

  • 写回答

2条回答 默认 最新

  • douningqiu4991 2011-08-10 00:57
    关注

    I am not sure exactly what that function checks in the database but one idea to speed things up might be to get the line numbers in database BEFORE the foreach loop. Get all the line numbers in an array, inside the loop just check if the line number is in the array , if it is then use the highlight otherwise the normal case. This way you only query the database once instead of ~5k times.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了