使用php将数据从db转换为JSON [英] Convert data from db to JSON using php

查看:147
本文介绍了使用php将数据从db转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过很多问题,但没有什么帮助。
我想使用PHP将我的数据从数据库(MySQL)转换为JSON。这是我的PHP代码:

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);

?>

错误是 0

推荐答案

代码中有很多问题。对于初学者,您有:

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 c> mysqli_result 对象成功或布尔 false 失败。这里,它是false,因为你没有传递数据库链接( $ con )。请参见文档。您不应该,不需要,不能 mysqli_query 的结果存储在变量( $ sql ),然后在另一个调用中传递该变量到 mysqli_query 。只要执行:

$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;
}

也许你的意思是 $ output = array );

您将从使用像PHPStorm这样的IDE中获益。

You would benefit from using an IDE like PHPStorm.

这篇关于使用php将数据从db转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆