php mysqli 查询数据库输出json

<?php
header("Content-type:text/json;charset=utf-8");//字符编码设置  
$mysqli = new mysqli("localhost", "root", "123456", "testdb");
/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
$results = array();
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * from testtb")) {
    while($row=$result->fetch_row()){ 
        array_push($results,$row); 
    }
    $result->close();
}
else
{
    echo $mysqli->error;  
}

echo json_encode($results);  //return json data

$mysqli->close();
?>

 

posted @ 2022-06-11 16:02  devgis  阅读(255)  评论(0)    收藏  举报