PHP Mysqli 返回json格式

时间:2021-10-31 07:14:15

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/12/9
 * Time: 16:17
 */

$host="127.0.0.1";
$username="root";
$passwd="root";
$dbname="phpmysql";


$mysqli=new mysqli($host,$username,$passwd,$dbname);
if($mysqli->error){
    die("connect error,the error num is".$mysqli->connect_errno."the error message is" .$mysqli->connect_error);
}

$id=$_GET["id"];
//设置编码集
$mysqli->set_charset("Utf-8");

//写sql
$sql=‘select * from user where id=?‘;


$stmt=$mysqli->prepare($sql);


$stmt->bind_param("i",$id);

$stmt->execute();

$re=$stmt->get_result();


$array=array();
$inum=0;
while ($row=$re->fetch_assoc()){
    $array[$inum]=$row;
    $inum  ;
}

$data=array();
$data[‘cont‘]=$array;
$data=json_encode($data);
header(‘content-type:application/json‘);
echo $data;

$re->close();
$stmt->close();