PHP怎么转化json?

查询女性用户并且将数组转成json

image.png

(1)在index.php页面,使用 PDO 方式,链接操作 MySQL 数据库。

(2)查询注册时间[registration_time]大于等于 2020-09-01以后的女性用户

        并且据用户注册时间升序排序。

(3)用fetchALL(PDO::FETCH_ASSOC)方法从结果集中只获取关联下标的数据

         赋值给变量$result

(4)将变量$result内数组转换成json复制给变量 $json_str

(5)输出变量 $json_str

    

 用户表[user]说明:

    id                           序号,

    uname                   用户名称,

    upwd                     用户密码,

    sex                         性别,

    registration_time   注册时间,

我的代码:

<?php 
header("content-type:text/html;charset=utf-8");
//$url,$user,$pwd是自动生成的数据库相关信息,不能修改
//连接数据库时不需要写端口号
$url = "mysql:host=mysql;dbname=database_25523_19_91539";//数据库ip和库名
$user = "25523_19_91539";//数据库用户
$pwd = "12ae0f4921c12ba208081909bfc6660c";//数据库密码


$sql="select * from user order by user.registration_time >= 2020-09-01 asc";
$conn=new PDO($url,$user,$pwd);
$result=$conn->query($sql)->fetchALL();
 

 
 
echo $json_str;

<?php 
header("content-type:text/html;charset=utf-8");
//$url,$user,$pwd是自动生成的数据库相关信息,不能修改
//连接数据库时不需要写端口号
$url = "mysql:host=mysql;dbname=database_25523_19_91539";//数据库ip和库名
$user = "25523_19_91539";//数据库用户
$pwd = "12ae0f4921c12ba208081909bfc6660c";//数据库密码
$sql="select * from user where registration_time>='2020-09-01' and sex='女' order by registration_time";
$conn=new PDO($url,$user,$pwd);
$result=$conn->query($sql)->fetchALL(PDO::FETCH_ASSOC);
$json_str=json_encode($result);
echo $json_str;
?>