douzhang3822 2013-03-13 18:11
浏览 81

PHP:我的页面需要很长时间才能加载但不会超时。 是一次查询太多还是我的代码可以优化?

This is the function I use to access the DB, theoretically maybe up 10-20 times in a do while loop, though right now I removed the loop so it only can do one db query at a time. Can this be optimized more or is this how transactions and commits are properly done? Also, I don't know what $db->rollBack() actually does, I just saw it on a stackoverflow

<?php
  function util_db_access($statement, $array) {
    $db = new PDO('mysql:host=localhost;dbname=db;charset=UTF8', 'user', 'pass');

    try {
      //echo "1";
      $db->beginTransaction();
      //echo "2";
      $stmt = $db->prepare($statement);
      //echo "3"; 
      if($stmt->execute($array)) {
        $db->commit();
        //echo "4";
        if($rows = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
          //echo "5";
          if($stmt->rowCount() < 2) {
            $rows = $rows[0]; 
          }
          return $rows;
        } else {
          //echo "6.1";
          //$db->commit();
          return true;
        }
      } else {
        //echo "6.2";
        //$db->commit();
        return false;
      }
    } catch(PDOException $e) {
      $db->rollBack();
      //log, we are gonna keep a log eventually.. right?
      return -1;
    }
  }
?>
  • 写回答

4条回答 默认 最新

  • douxianglu4370 2013-03-13 18:16
    关注

    Try using a profiler to determine where your bottleneck is - there's one included in xdebug. Given the simplicity of this code, it may be the query itself - try running the query standalone, either using the mysql cli client or MySQL Workbench, and see what timings you get back. If it is the query that's slow, you can use EXPLAIN and the bountiful optimization sections in the MySQL manual to improve it.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入