Home  >  Article  >  Backend Development  >  How to get data from database in php

How to get data from database in php

王林
王林Original
2019-09-24 13:04:235621browse

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;
}

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

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!

Statement:
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