The first step is to define relevant variables
$servername = "localhost"; $username = "root"; $password = "root"; $mysqlname = "datatest"; $json = ''; $data = array(); class User { public $id; public $fname; public $lname; public $email; public $password; }
The second step is to link the database, the code is as follows:
// 创建连接 $conn = mysqli_connect($servername, $username, $password, $mysqlname);
The third step is to define the query statement and execute it. The code is as follows:
$sql = "SELECT * FROM userinfo"; $result = $conn->query($sql);
The fourth step is to obtain the queried data and put it in In the class declared in advance, the final output is in json format. The code is as follows:
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 "查询失败"; }
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to read data from database in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
