doucheng1884 2014-04-10 14:55
浏览 31
已采纳

如何将结果行添加到json对象

Im using ajax to update my data. Ajax calls my function.php where i use a switch to determent which function to run. I save my results in a json object ($resp = new stdClass). But how do i save multiple rows (with multiple columns) into the json object?

function func1($mysqli){
    $result = $mysqli->query("select * from order");

    ///how do i fetch all rows in a loop and save it correctly to my json object?

    return json;
}

$resp = new stdClass;

if (isset($_POST["action"])) {
    switch($_POST["action"])) {
    case "func1":
        $resp->data = func1($mysqli);
        break;
    }
}
echo json_encode($resp);
  • 写回答

1条回答 默认 最新

  • dongyou5068 2014-04-10 14:59
    关注

    Here is the function which stores rows in an array and returns it. If query fails, null is returned.

    function func1($mysqli){
        $result = $mysqli->query("select * from `order`");
    
       if ($result){
         $data = array();
    
         while($row = $result->fetch_assoc()){
           $data[] = $row ;
         }
    
         return $data ;
    
       } else {
         return null ;
       }
    }
    

    In your code you already save a return value in a STDClass, so it is fine:

    case "func1":
        $resp->data = func1($mysqli);
        break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?