2015-07-20 74 views
0

我想從使用Json的Mysql數據庫發送數據。只要它在數據庫中只有1個職位,但是當它的行數更多時,它也不再工作。使用PHP發送數據從Mysql與Json使用PHP

這是PHP代碼: // array for JSON response $ response = array();

$data = new CDatabaseInfo(); 
$result = $data ->selectAll(); 
$data->closeDatabase(); 

// check for empty result 
if (isset($result)) { 

    $response["products"] = array(); 
    foreach($result as $value) { 
     $product = null; 
     $product = array(); 
     $product["pid"] = $value["pid"]; 
     $product["name"] = $value["name"]; 
     $product["price"] = $value["price"]; 
     $product["description"] = $value["description"]; 
     $product["created_at"] = $value["created_at"]; 
     $product["updated_at"] = $value["updated_at"]; 
     array_push($response["products"], $product); 
    } 
    // success 
    $response["success"] = 1; 
    echo json_encode($response, TRUE); 
    echo "var dump <br>"; 
    var_dump($response); 
} 

這裏來的var_dump結果:

array(2) { ["products"]=> array(2) {[0]=> array(6) { ["pid"]=> string(1) "1" ["name"]=> string(6) "Festis" ["price"]=> string(5) "20.00" ["description"]=> string(9) "God dryck" ["created_at"]=> string(19) "2015-07-09 20:31:30" ["updated_at"]=> string(19) "0000-00-00 00:00:00" } [1]=> array(6) { ["pid"]=> string(1) "4" ["name"]=> string(4) "Cola" ["price"]=> string(5) "12.00" ["description"]=> string(11) "En fin läsk" ["created_at"]=> string(19) "2015-07-20 20:29:03" ["updated_at"]=> string(19) "0000-00-00 00:00:00" } } ["success"]=> int(1) } 

謝謝!

回答

0

有沒有這樣的事情json_encode($response, TRUE);

要確保你從數據庫中獲取正確的數據。除了這個小小的錯誤,你的代碼應該正常運行。

+0

我拿走TRUE但仍然不適用於大於1行的數組。當它只有1行時,它的作品完美 – Thurex

+0

我只是用$ result中的一些隨機數據運行你的代碼,並且它工作正常。 – Hedam

+1

我拿走了$ response [「products」] = array();並輸入:$ response = array();相反,那麼我只是輸入:$ response [] = $ value;在foreach迭代中。 – Thurex