在mysqli Prepared Statement上获取json_encode()的问题

时间:2015-07-17 05:58:38

标签: php mysqli prepared-statement

我在使用MySQLi导出Prepared Statement的结果时遇到了一些问题。

$age = "young";
$rows = array();
$mysqli = new mysqli($db_hostname, $db_username, $db_password, $db_database);

        $stmt = $mysqli->prepare("SELECT fname, lname FROM users WHERE age=?");
        $stmt->bind_param('s', $age);
        $stmt->execute();
        $stmt->bind_result($thefName,$thelName);
                while($stmt->fetch()) 
                  {
                    array_push($rows, $thefName,$thelName);
                  }
            $stmt->close();

$mysqli->close();
echo json_encode($rows);

正如您所看到的,我正在尝试将每个行的json_encode($rows);作为JSON数组回显如下:

[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"}, 
    {"firstName":"Peter","lastName":"Jones"}
]

但我得到的是

["John", "Doe", "Anna", "Smith", "Peter", "Jones"] 

你能告诉我为什么会这样,以及如何解决它

1 个答案:

答案 0 :(得分:1)

推送正确的数组 -

array_push($rows, array('firstName' => $thefName, 'lastName' => $thelName));