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!