How to get data from database in php

王林
Release: 2023-02-24 17:32:01
Original
5609 people have browsed it

How to get data from database in php

In php, read data from the database and return the data in json format. The specific method is as follows:

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 place it in the pre-statement In the class, the final output is in json format

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 get 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!