【问题标题】:MySQL & PDO : about efficiencyMySQL & PDO:关于效率
【发布时间】:2012-04-12 23:21:57
【问题描述】:

我有以下代码:

<?php
try {
  # MySQL with PDO_MYSQL
  $DBH = new PDO("mysql:host=*****;dbname=****", "****", "*****");
  $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

  # statement handle (prevents injection)
  $STH = $DBH->prepare("SELECT Adresse FROM Agences");
  $STH->execute();

  # statement handle (prevents injection)
  $STHNAMES = $DBH->prepare("SELECT `numero-agence` FROM Agences");
  $STHNAMES->execute();

  $storeArray = Array();
  $nameArray = Array();
  while ($row = $STH->fetch()) {
      $storeArray[] =  $row['Adresse'];  
  }

  while ($row = $STHNAMES->fetch()) {
      $nameArray[] =  $row['numero-agence'];  
  }

  echo json_encode(
    Array("theAddress" => $storeArray,
    "theName" => $nameArray)
  );
}
catch(PDOException $e) {
    echo 'There was an issue inserting thing into database: '.$e->getMessage();
}
?>

我的问题是:有没有办法将这两个查询结合起来,并且仍然有一个关联数组以 JSON 编码发送回客户端? (我正在使用 ajax 调用查询这部分 PHP,并且需要结果数据)

谢谢。

【问题讨论】:

    标签: mysql ajax pdo


    【解决方案1】:

    可以在同一个查询中完成:

         # statement handle (prevents injection)
          $STH = $DBH->prepare("SELECT Adresse, `numero-agence` FROM Agences");
          $STH->execute();
    
          $storeArray = Array();
          $nameArray = Array();
          while ($row = $STH->fetch()) {
              $storeArray[] =  $row['Adresse'];  
              $nameArray[] =  $row['numero-agence'];  
          }
    

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 2012-06-18
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2016-09-02
      • 1970-01-01
      相关资源
      最近更新 更多