php Method for reading data from a database and returning data in json format

  • 2021-10-27 06:42:55
  • OfStack

In php, data is read from the database and returned in json format. The specific methods are as follows:

Step 1, define related variables


$servername = "localhost";
$username = "root";
$password = "root";
$mysqlname = "datatest"; 
$json = '';
$data = array();
class User 
{
public $id;
public $fname;
public $lname;
public $email;
public $password;
}

Step 2, link the database, the code is as follows:


//  Create a connection 
$conn = mysqli_connect($servername, $username, $password, $mysqlname);

Step 3, define the query statement and execute it. The code is as follows:


$sql = "SELECT * FROM userinfo";
$result = $conn->query($sql);

Step 4: Obtain the queried data, put it in a pre-declared class, and finally output it in json format.

The code is as follows:


if($result){
//echo " Query succeeded ";
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);// Convert data into JSON Data .
echo "{".'"user"'.":".$json."}";
}else{
echo " Query failed ";
}

Related articles: