用PHP从SQL数据格式化JSON对象


Formatting JSON Object with PHP from SQL data

我从我的PHP脚本得到这个结果:

{
   "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":[
   ]
}

可以看到,这里有两个问题:user中的所有键都是。并宣布数组为空。

这是我的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();
}
?>
  • 为什么我在JSON对象中为用户键中的每个键获得2个条目?
  • 为什么我的公告数组是空的?是否有任何问题,当我试图得到用户的是运行我的第二个SQL请求?

第一个问题是fetchAll()默认为PDO::FETCH_BOTH,它同时得到关联和数值结果。修改对fetchAll(PDO::FETCH_ASSOC)的调用,这将只返回关联键。

第二个问题是:

$id_user = $arrAllUser[0];

这里,$id_user是一个数组。要获取在其他查询中使用的用户ID,您需要:

$id_user = $arrAllUser[0]['id'];
  1. 你必须使用$result1->fetchAll();参数PDO::FETCH_COLUMN
  2. 第二次查询有结果吗?