2014-05-22 49 views
1

我從我的PHP腳本得到這樣的結果:格式JSON對象與PHP從SQL數據

{ 
    "user":{ 
     "id":"1", 
     "0":"1", 
     "username":"test1", 
     "1":"test1", 
     "password":"pwd1", 
     "2":"pwd1", 
     "nom":"LUC", 
     "3":"LUC", 
     "prenom":"FOI", 
     "4":"FOI", 
     "ville":"Paris", 
     "5":"Paris", 
     "avatar":"avatar1", 
     "6":"avatar1" 
    }, 
    "annonces":[ 

    ] 
} 

正如你所看到的,有2問題:在用戶的所有按鍵都。 annonces數組是空的。

這裏是我的PHP腳本:

<?php 
$PARAM_hote='aaaa'; 
$PARAM_port='3306'; 
$PARAM_nom_bd='bbbbbbb'; 
$PARAM_utilisateur='ccccccccc'; 
$PARAM_mot_passe='dddddddd'; 
// Create connexion to BDD 
$connexion = new PDO('mysql:host='.$PARAM_hote.';port='.$PARAM_port.';dbname='.$PARAM_nom_bd, $PARAM_utilisateur, $PARAM_mot_passe); 

try { 

    // Getting username/password 
    $username = $_POST['username']; 
    $password = $_POST['password']; 

    // Prepare SQL request to check if the user is in BDD 
    $result1=$connexion->prepare("select * from tbl_user where username = '".$username."' AND password = '".$password. "'"); 
    $result1->execute(); 

    // Getting all results in an array 
    $arrAllUser = $result1->fetchAll(); 

    // If the size of array is equal to 0, there is no user in BDD 
    if (sizeof($arrAllUser) == 0) { 
     echo "fail"; 
    } 
    // In this case, a user has been found, create a JSON object with the user information 
    else { 

     // Getting id of the user 
     $id_user = $arrAllUser[0]; 

     // Prepare a second SQL request to get all annonces posted by the user 
     $result2=$connexion->prepare(" select * from annonces where id_author = '".$id_user."' "); 
     $result2->execute(); 

     // Getting all annonces posted by the user in an array 
     $arrAllAnnonces = $result2->fetchAll(); 

     // Set in key user the USER structure 
     $array['user'] = $arrAllUser[0]; 
     // Set in key annonces all annonces from the user 
     $array['annonces'] = $arrAllAnnonces; 

     // JSON encore the array 
     $json_result = json_encode($array); 
     echo $json_result; 
    } 

} catch(Exception $e) { 
    echo 'Erreur : '.$e->getMessage().'<br />'; 
    echo 'N° : '.$e->getCode(); 
} 

?> 
  • 爲什麼我'獲得2項爲JSON對象在用戶密鑰每個鍵?
  • 爲什麼我的annonces數組是空的?當我嘗試讓用戶運行我的第二個SQL請求時,是否有任何問題?

回答

1

第一個問題是fetchAll()默認爲PDO::FETCH_BOTH它可以獲得關聯和數字結果。將呼叫更改爲fetchAll(PDO::FETCH_ASSOC),僅返回關聯密鑰。

第二個問題是這樣的:

$id_user = $arrAllUser[0]; 

這裏,$id_user是一個數組。要獲得用於其他查詢的用戶ID,您需要:

$id_user = $arrAllUser[0]['id']; 
+0

非常感謝。它解決了我的問題! – wawanopoulos

0
  1. 你必須使用$result1->fetchAll();與PARAM PDO::FETCH_COLUMN
  2. 你得到從第二個查詢任何結果?