Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

php - How to convert mysqli result to JSON?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {

    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $myArray[] = $row;
    }
    echo json_encode($myArray);
}

$result->close();
$mysqli->close();
  1. $row = $result->fetch_array(MYSQLI_ASSOC)
  2. $myArray[] = $row

output like this:

[
    {"id":"31","name":"pruduct_name1","price":"98"},
    {"id":"30","name":"pruduct_name2","price":"23"}
]

If you want another style, you can try this:

  1. $row = $result->fetch_row()
  2. $myArray[] = $row

output will like this:

[
    ["31","pruduct_name1","98"],
    ["30","pruduct_name2","23"]
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...