【发布时间】:2014-07-11 11:04:00
【问题描述】:
我从我的 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":[
]
}
如您所见,有两个问题:用户中的所有键都是。并且 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();
}
?>
- 为什么我会为 JSON 对象中用户键中的每个键获得 2 个条目?
- 为什么我的 annonces 数组是空的?当我尝试获取用户的身份以运行我的第二个 SQL 请求时有什么问题吗?
【问题讨论】: