Home > Backend Development > PHP Problem > How to read data from database in php

How to read data from database in php

王林
Release: 2023-02-25 19:42:02
Original
7597 people have browsed it

How to read data from database in php

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;
}
Copy after login

The second step is to link the database, the code is as follows:

// 创建连接
$conn = mysqli_connect($servername, $username, $password, $mysqlname);
Copy after login

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);
Copy after login

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 "查询失败";
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template