dongtong2021 2016-07-28 14:32 采纳率: 0%
浏览 31
已采纳

正确的json格式的数据

I am working on a feature of my website where I need to trigger an ajax call on the click of button. I am receiving data in this format:

Object {
    name: "abc",
    category_id: "1"
}

I want a result like this:

{
    "list" : [
        {
            "name" : "xyz",
            "category_id" : "1"
        }, {
            "name" : "abc",
            "category_id" : "11"
        }
    ]
}

my server side code is:

<?php

header('Content-Type: application/json');

$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));

while($row = mysqli_fetch_array($result)) {
    $name = $row['name'];
    $category = $row['category_id'];
}
$data = array("name" => $name , "category_id" => $category );
echo json_encode($data);
?>
  • 写回答

3条回答 默认 最新

  • du4373 2016-07-28 14:42
    关注

    Before, you were assigning $row array items to variables, and then not using them until after the loop. After the loop, you used those variables, but it would only have the last values. You must append your items to an array ('list') inside of your array and then json_encode() your result from the loop to get the desired effect.

    <?php
    $conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
    $name = $_GET['name'];
    header('Content-Type: application/json');
    $sql = "SELECT * from test_search where name = '$name'";
    $result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
    
    $data_array = array('list' => array());
    while($row = mysqli_fetch_array($result))
    {
        $data_array['list'][] = array("name" => $row['name'], "category_id" => $row['category_id'] );
    }
    echo json_encode($data_array);
    ?>
    

    Untested code, apologies for any syntax errors.

    I would also like to point out that your code is open to SQL injection attacks. Follow the link to the PHP Manual to learn more about these and how to prevent them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?