时间:2021-07-01 10:21:17 帮助过:38人阅读
第一步、定义相关变量
$servername = "localhost"; $username = "root"; $password = "root"; $mysqlname = "datatest"; $json = ''; $data = array(); class User { public $id; public $fname; public $lname; public $email; public $password; }
第二步、链接数据库,代码如下:
// 创建连接 $conn = mysqli_connect($servername, $username, $password, $mysqlname);
第三步、定义查询语句,并执行,代码如下:
$sql = "SELECT * FROM userinfo"; $result = $conn->query($sql);
第四步、获取查询出来的数据,并将其放在事先声明的类中,最后以json格式输出。代码如下:
if($result){ //echo "查询成功"; while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) { $user = new User(); $user->id = $row["id"]; $user->fname = $row["fname"]; $user->lname = $row["lname"]; $user->email = $row["email"]; $user->password = $row["password"]; $data[]=$user; } $json = json_encode($data);//把数据转换为JSON数据. echo "{".'"user"'.":".$json."}"; }else{ echo "查询失败"; }
推荐教程:PHP视频教程
以上就是php怎么从数据库读取数据的详细内容,更多请关注Gxl网其它相关文章!