2016-05-16 21 views
1

我已經使用下面的代碼從我的數據庫中提取數據並將其轉換爲數組。我的問題是echo json_encode函數不起作用,並且在運行此代碼時(沒有print_r函數),我留下了一個空白頁面。使用PHP將SQL查詢中的項目數組轉換爲JSON

$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 

    ) 

謝謝。

+0

你有沒有想過你錯過了第一行關閉字符串的報價? – NoImaginationGuy

+0

This [LINK](http://stackoverflow.com/a/19366999/4018240)可能對您有所幫助... –

+0

謝謝@ManjeetBarnala問題解決了。我研究了這一點,並通過添加以下內容來解決它:mysqli_set_charset($ connection,「utf8」); – Brett

回答

0

你忘了在這條線加雙引號:

$query = "SELECT * From table;

因爲內部服務器錯誤的和已經發生。

第一行代碼應該是這樣的

$query = "SELECT * From table";

+0

好點,但這不是問題。我編輯$查詢時粘貼到堆棧溢出,使代碼更清晰,但錯過了結尾「。我正在運行的代碼有這個,它的查詢是在數據庫中執行。我有問題轉換我的數組到JSON。 – Brett

+0

請檢查以上答案 – user6123296

0
$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); 
0

$康恩= mysqli_connect( 「本地主機」, 「根」, 「根」, 「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);
}