[英]Converting an array of items from SQL query into JSON using PHP
我使用下面的代碼從我的數據庫中提取數據並將其轉換為數組。 我的問題是echo json_encode函數不起作用,並且在運行此代碼時(沒有print_r函數)我留下了一個空白頁面。
$query = "SELECT * From table";
$resultarray = array();
if ($result = mysqli_query($connection, $query)) {
while ($row = mysqli_fetch_row($result)) {
$resultarray[] = $row;
}
print_r($resultarray); // This line shows that the array is works but the code below does not convert to JSON.
echo json_encode($resultarray);
}
我使用了print_r函數來確保我在代碼中創建了一個數組。 我已經圈了幾個小時,我不明白我做錯了什么。 如果我使用print_r函數並查看頁面源代碼,我會得到以下內容:
Array
(
[0] => Array
(
[0] => 5
[1] => Name 1
[2] => Description 1
[3] => Location 1
)
[1] => Array
(
[0] => 6
[1] => Name 2
[2] => Description 2
[3] => Location 2
)
[2] => Array
(
[0] => 45
[1] => Name 3
[2] => Description 3
[3] => Location 3
)
謝謝。
你忘了在這一行添加雙引號:
$query = "SELECT * From table;
並且因為發生了內部服務器錯誤。
第一行代碼應該是這樣的
$query = "SELECT * From table";
$con = mysqli_connect("localhost", "username", "password", "dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql ="SELECT * FROM `table_name`";
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_row($result)) {
$resultarray[] = $row;
}
echo json_encode($resultarray);
}
mysqli_close($con);
$ conn = mysqli_connect(“localhost”,“root”,“root”,“db_rest”);
$ query =“SELECT * From users”;
$ resultarray = array();
if($ result = mysqli_query($ conn,$ query)){
while($ row = mysqli_fetch_row($ result)){
$ resultarray [] = $ row;
}
echo json_encode($ resultarray);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.