2012-03-29 73 views
0

我有以下代碼:的MySQL和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的這一點,並需要得到的數據)

謝謝。

回答

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

那偉大工程,謝謝! – Krimo 2012-03-30 06:46:53