php把mysql数据转成json格式的方法:首先mysql测试数据库表,并新建【testmysql.php】文件来测试;然后用数据库执行查询语句;接着将数据放到user对象中;最后用【json_encode】函数将数据转换成json格式。
【相关学习推荐:php编程(视频)】
php把mysql数据转成json格式的方法:
1、首先mysql测试数据库表
CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户编号', `login_name` varchar(50) NOT NULL COMMENT '用户名', `usable` int(11) NOT NULL DEFAULT '1' COMMENT '是否可用 0:不可用;1:可用', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `last_login_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后登录时间', PRIMARY KEY (`id`), UNIQUE KEY `login_name` (`login_name`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户表';
2、在idea开发工具中新建一个testmysql.php文件来测试
创建mysql连接 $link = mysql_connect('xxx:3306', 'root', 'xxx'); if (!$link) { echo "fail"; }
3、选择数据库,执行查询语句,$result接收返回的数据内容
mysql_select_db("study"); $result = mysql_query("select * from t_user");
4、定义一个user对象
class User { public $login_name; public $usable; public $create_time; }
5、循环读出数据放到user对象中
$data = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $user = new User(); $user->login_name = $row["login_name"]; $user->usable = $row["usable"]; $user->create_time = $row["create_time"]; $data[] = $user; }
6、使用json_encode函数将数组数据转换成json格式,然后echo打印出来
$json = json_encode($data);echo "{" . '"user"' . ":" . $json . "}";
7、右击选择Run运行,看看控制台运行之后打印结果
{"user":[{"login_name":"aa1","usable":"2","create_time":"2017-08-29 18:21:35"},{"login_name":"aa","usable":"1","create_time":"2017-08-29 18:22:30"}]}
信息成功从mysql中读出并转换成json格式打印了出来
完整示例代码如下:
<?php error_reporting(E_ALL || ~E_NOTICE); $link = mysql_connect('xxx:3306', 'root', 'xxx'); if (!$link) { echo "fail"; } mysql_select_db("study"); $result = mysql_query("select * from t_user"); class User { public $login_name; public $usable; public $create_time; } $data = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $user = new User(); $user->login_name = $row["login_name"]; $user->usable = $row["usable"]; $user->create_time = $row["create_time"]; $data[] = $user; } $json = json_encode($data); echo "{" . '"user"' . ":" . $json . "}";
想了解