2016-09-17 39 views
0

我試圖從我的LAMP服務器獲取產品數據。但我沒有得到迴應。問題似乎是array_push不能正常工作,因爲我可以在使用echo之前打印數據。php:無法爲數組賦值並將其作爲響應傳遞

我對PHP相當陌生。

感謝您的提前幫助。

<?php 
ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "DB"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "SELECT * FROM Produkt"; 
$result = $conn->query($sql); 


// check for empty result 
if (mysqli_num_rows($result) > 0) { 

    // looping through all results 
    // products node 
    $response["products"] = array(); 

    while ($row = mysqli_fetch_assoc($result)) { 
     // temp user array 
     $product = array(); 
     $product["ID"] = $row["ID"]; 
    $product["Name"] = $row["Name"]; 


     // push single product into final response array 
      //print json_encode($product); 
     array_push($response["products"], $product); 
    } 
    // success 
    $response["success"] = 1; 

    // echoing JSON response 
    echo json_encode($response); 
} else { 
    // no products found 
    $response["success"] = 0; 
    $response["message"] = "No products found"; 

    // echo no users JSON 
    echo json_encode($response); 
    //print json_encode($response); 
} 
?> 
+1

如果你只需從數據庫中選擇'ID'和'Name'(改變你的sql),你就可以執行'$ response ['products'] [] = $ row;'在while循環中 – Rasclatt

回答

1

您可以輕鬆簡單的代碼實現:

$i = 0; 
    while ($row = mysqli_fetch_assoc($result)) { 
     // temp user array 
     $product = array(); 
     $product["ID"] = $row["ID"]; 
    $product["Name"] = $row["Name"]; 


     // push single product into final response array 
      //print json_encode($product); 
     $response["products"][i] = $product; 
     $i++; 
    } 

或者你可以讓你自己的代碼,以及你想:)

1

待辦事項somethink像

<?php 
ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "DB"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "SELECT * FROM Produkt"; 
$result = $conn->query($sql); 

$array = array(); 
// check for empty result 
if (mysqli_num_rows($result) > 0) { 

    // looping through all results 
    // products node 

    while ($row = mysqli_fetch_assoc($result)) { 
     // temp user array 
      $array['products'][] = $row; 
     // push single product into final response array 
      //print json_encode($product) 
    } 
    // success 
    $array["success"] = 1; 

    // echoing JSON response 
    echo json_encode($array); 
} else { 
    // no products found 
    $array["success"] = 0; 
    $array["message"] = "No products found"; 

    // echo no users JSON 
    echo json_encode($array); 
    //print json_encode($array); 
} 
?>