MySQL& PDO:关于效率

时间:2012-03-29 10:08:18

标签: mysql ajax pdo

我有以下代码:

<?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,并且需要结果数据)

感谢。

1 个答案:

答案 0 :(得分:2)

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

     # 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'];  
      }