返回MySql对象,每行作为数组

时间:2014-10-23 03:36:19

标签: javascript php mysqli

我想查询我的数据库并获取一个数组数组。我将所有行合并为一个扁平数组,这使得我很难解析它。

PHP:

function conn($sQuery){
    $sMessage = '';
    $db = new mysqli('localhost','root','','db') or die('unable to connect!');
    if($db->connect_errno){
        $message = $db->connect_error;
    } else{
        if($db->query($sQuery)){
            $stmt = $db->prepare($sQuery);
            $stmt->execute();
            $oResult = $stmt->get_result();
            while($rows = $oResult->fetch_assoc()){
                foreach($rows As $value){
                    $aRows[] = $value;
                }
            }
            $oResult->free();
            $db->close();
            return $aRows;
        } else{
            $sMessage = $db->error;
            $db->close();
            return $sMessage;
        }
    }
}

function requestNote(){
    $sQuery = "SELECT * FROM `note` WHERE `sender_Id` = '" . $_SESSION['user_Id'] . "'";
    $oResult = conn($sQuery);
    if(!is_array($oResult)||!isset($oResult)||empty($oResult)||is_null($oResult)){
        echo null;
    } else{
        echo json_encode($oResult);
    }
}

JS:

request.done(function(oResult){
    var jsonResult = $.parseJSON(oResult);
    console.log("Json returned: ", jsonResult);
});

打印:

杰森回来了:

[1, 100000, 100000, "This is a test note inserted directly into DB", "2014-10-22 15:34:15", 2, 100000, 100000, "This is the second test ...serted directly into DB", "2014-10-22 21:56:50"]

我想要的是:

杰森回来了:

[

   [1, 100000, 100000, "This is a test note inserted directly into DB", "2014-10-22 15:34:15"], 

   [2, 100000, 100000, "This is the second test ...serted directly into DB", "2014-10-22 21:56:50"]

]

2 个答案:

答案 0 :(得分:0)

替换

while($rows = $oResult->fetch_assoc()){
     foreach($rows As $value){
         $aRows[] = $value;
     }
}

while($rows = $oResult->fetch_array(MYSQLI_NUM)) {
     $aRows[] = $rows;
}

fetch_array(MYSQLI_NUM)将返回一个简单的数组而不是关联数组,这样你的json数据就不会有对象了。

答案 1 :(得分:0)

您不需要foreach循环内的while循环。 while遍历行,因此foreach将迭代列。它应该只是:

        while($rows = $oResult->fetch_assoc()){
            $aRows[] = $rows;
        }