mySQLi数组直接到json数组

时间:2014-07-02 22:40:13

标签: php mysql arrays json mysqli

是否有可能让mysqli直接吐出一个数组然后用json_encode和php(用jquery检索)?

我的意思是..避免做一个while循环

我有这个:

    $sql = 'SELECT id, name FROM thetable';
    $stmt = $conn->prepare($sql);

    if ($stmt) {

        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $stmt->bind_result($sql_id, $sql_name);

            $json = array();

            while($row = $stmt->fetch()){
                $json[] = $sql_id.'=>'.$sql_name;
            }

            echo json_encode($json);

        }

    }

(这只是我代码的简短版本)

1 个答案:

答案 0 :(得分:1)

如果您的查询没有任何参数,您也可以避免使用预准备语句。这样的事情就足够了

header('Content-type: application/json');
echo json_encode(
    $conn->query('SELECT id, name FROM thetable')
         ->fetch_all(MYSQLI_ASSOC)
);
exit;

如果您确实需要该声明,请使用mysqli_stmt::get_result

$stmt = $conn->prepare($sql);
// $stmt->bind_param(...);
$stmt->execute();
$result = $stmt->get_result();

header('Content-type: application/json');
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
exit;