php: 无法为数组赋值并将其作为响应传递

php: Can't assign values to array and pass it as respone

我正在尝试从我的 LAMP 服务器获取产品数据。但我没有得到回应。问题似乎是 array_push 无法正常工作,因为我可以在此之前使用 echo 打印数据。

我对 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);
}
?>

做类似的事情

<?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);
}
?>

你可以用简单的代码轻松实现:

    $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++;
    }

或者您可以随心所欲地编写自己的代码:)