php中,从数据库读取数据,并以json格式返回数据。具体方法如下:
第一步,定义相关变量
$servername = "localhost";
$username = "root";
$password = "root";
$mysqlname = "datatest";
$json = '';
$data = array();
class User
{
public $id;
public $fname;
public $lname;
public $email;
public $password;
}
|
第二步,链接数据库,代码如下:
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $mysqlname);
|
第三步,定义查询语句,并执行,代码如下:
$sql = "SELECT * FROM userinfo";
$result = $conn->query($sql);
|
第四步,获取查询出来的数据,并将其放在事先声明的类中,最后以json格式输出。代码如下:
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 "查询失败";
}
|