使用JSON从数据库中获取信息

时间:2017-09-08 03:32:35

标签: php mysql json

亲爱的Coders / Hacker / Programmers。我需要一些帮助。我正在使用下面的代码从MySQL数据库中获取Info。这是PHP代码:

<?php
ini_set("display_errors", true);
ini_set("html_errors", false);
require "conn.php";
$query=mysqli_query($conn,"SELECT * FROM UserData");

if ($query){
    while($row=mysqli_fetch_array($query)){
        $flag[] =$row;


    }
    print(json_encode($flag));


}
mysqli_close($conn);
return $flag;
?>

这是我的数据库:

id|username|password|likedOne|likedTwo|likedThree|likedFour|likedFive
1 |NetsGets|Test    |        |        |          |         |

代码打印出来:

{"0":"1","id":"1","1":"netsgets","username":"netsgets","2":"test","password":"test","3":"","likedOne":"","4":"","likedTwo":"","5":"","likedThree":"","6":"","likedFour":"","7":"","likedFive":""}

我希望它是这样的:

{"id":"1","username":"netsgets","password":"test","likedOne":"","likedTwo":"","
likedThree":"","likedFour":"","likedFive":""}

(就像它应该是!!!)

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:3)

假设连接正常并且它正确地获取数据,您可以改为使用mysql_fetch_assoc:

<?php
ini_set("display_errors", true);
ini_set("html_errors", false);
require "conn.php";
$query=mysqli_query($conn,"SELECT * FROM UserData");

if ($query){
    while($row=mysqli_fetch_assoc($query)){
        $flag[] =$row;


    }
    print(json_encode($flag));


}
mysqli_close($conn);
return $flag;
?>

如果您有选择,我个人会转移到PDO,因为它允许您更好的数据库抽象