PHP json_encode() in while loop

后端 未结 3 1707
花落未央
花落未央 2021-01-01 07:53

I am trying to use json_encode() in a while loop while getting database results. Here is my code:



        
相关标签:
3条回答
  • 2021-01-01 08:32

    Try:

    <?
    
    $database = sqlite_open("thenew.db", 0999, $error);
    if(!$database) die($error);
    
    $query = "SELECT * FROM users";
    $results = sqlite_query($database, $query);
    if(!$results) die("Canot execute query");
    
    $data = array();
    
    while($row = sqlite_fetch_array($results)) {
      $data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
    }
    echo json_encode(array("response"=>$data));
    
    sqlite_close($database);
    
    ?>
    
    0 讨论(0)
  • 2021-01-01 08:33

    Push each user to an array:

    $data = array();
    while($row = sqlite_fetch_array($results)) {
      $data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
    }
    echo json_encode(array("response"=>$data));
    
    0 讨论(0)
  • 2021-01-01 08:34

    Change this

    while($row = sqlite_fetch_array($results)) {
      $data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
    }
    

    to

    $data = array();
    while($row = sqlite_fetch_array($results)) {
      $data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
    }
    
    0 讨论(0)
提交回复
热议问题