我的php文件没有以JSON格式返回所有值

时间:2016-02-13 13:08:20

标签: php mysql json post

所以我有一个数据库,我编写了一个php文件,可以将值插入table,然后返回此table中的所有值。

但是,我的代码只返回表中的一个随机值,而不是全部。我不知道为什么,但这是我的代码:

<?php
include_once "init.php";

if(!empty($_POST['names'])){
    $contactname = $_POST['names'];

    $query = "INSERT INTO contacts (contactID, names) 
                VALUES('NULL', ?)";
    $results = $conn -> prepare($query);
    $results->bind_param('s', $contactname);
    $results->execute();
    $results->close();
    echo json_encode("Success"); 

    $query_two = "SELECT names FROM contacts";
    $result = mysqli_query($conn, $query_two);
    $response = array();

    if(mysqli_num_rows($result)){
        while($row = mysqli_fetch_assoc($result)){
            $response["names"][] = $row["names"];
        }
    }
    echo json_encode($response);
}
else{
    echo json_encode("Something went wrong");
}

?>
编辑:谢谢你们这么快就为我提供解决方案!我修复它并且它可以正常工作,但第一个echo json_encode("Success");没有被执行。

1 个答案:

答案 0 :(得分:2)

在这里:

$response["names"] = $row["names"];

您正在替换$response["names"]的值。相反,请尝试将其添加到数组中:

$response = array("names" => array());

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_assoc($result)){
        $response["names"][] = $row["names"];
    }
}

要使用一个JSON对象,您需要在顶部初始化$response并根据需要更改值。

<?php
include_once "init.php";

$response = ['success' => false, 'message' => null, 'names' => []];

if(empty($_POST['names'])) {
    $response['message'] = 'No names were provided in the request';

} else {
    $contactname = $_POST['names'];

    $query = "INSERT INTO contacts (contactID, names) VALUES('NULL', ?)";
    $results = $conn->prepare($query);
    $results->bind_param('s', $contactname);
    $results->execute();
    $results->close();

    $response['success'] = true;

    $query_two = "SELECT names FROM contacts";
    $result = mysqli_query($conn, $query_two);

    if(mysqli_num_rows($result)){
        while($row = mysqli_fetch_assoc($result)){
            $response['names'][] = $row['names'];
        }
    }

}

echo json_encode($response);