dszn2485 2016-03-08 19:28
浏览 41
已采纳

使用php将数据从db转换为JSON

I have already seen many questions but nothing has helped. I want to convert my data from database (MySQL) to JSON using PHP. This is my PHP code:

init.php

<?php
$db_name = "webappdb";
$mysql_user = "root";
$mysql_pass = "root";
$server_name = "localhost";
$charset= "utf8";

$con = mysqli_connect($charset, $server_name, $mysql_user, $mysql_pass, $db_name);
?>

listViewBooks.php

<?php

include("init.php");

header('Content-Type: application/json');

// get all items from user_info_book table
$sql = mysqli_query("SELECT * FROM `user_info_book`");

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
    $output[] = $row;
}

echo json_encode($output);
echo json_last_error();

mysqli_close($con);

?>

The error is 0, so it's nothing.

  • 写回答

4条回答 默认 最新

  • douyue8685 2016-03-08 19:34
    关注

    There are a bunch of problems in your code. For starters, you have this:

    $sql = mysqli_query("SELECT * FROM `user_info_book`");
    
    $res = mysqli_query($con,$sql);
    

    $sql is a mysqli_result object on success or boolean false on failure. Here, it's false because you didn't pass the database link ($con). See the docs. You shouldn't, don't need to, and can't store the result of mysqli_query in a variable ($sql) and then pass that variable in another call to mysqli_query. Just do:

    $sql = "SELECT * FROM `user_info_book`";
    
    $res = mysqli_query($con, $sql);
    

    Also, you initialize one array, then add to another:

    $result = array();
    
    while($row = mysqli_fetch_array($res)){
        $output[] = $row;
    }
    

    Perhaps you mean to do $output = array();?

    You would benefit from using an IDE like PHPStorm.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)