直接将mySQLi数组转换为json数组 [英] mySQLi array directly to json array

查看:68
本文介绍了直接将mySQLi数组转换为json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to get mysqli to spit out an array directly that I then json_encode with php (to retrieve with jquery) ?

我的意思是..避免进行while循环

I mean.. avoid making a while loop

我有这个:

    $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);

        }

    }

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

(this is just a simplyfied short version of my code)

推荐答案

如果查询没有任何参数,则最好避免使用准备好的语句.这样的东西就足够了

If your query does not have any parameters, you might as well avoid using the prepared statement. Something like this should suffice

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

如果确实需要该语句,请使用 mysqli_stmt :: get_result

If you do need the statement, use 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;

这篇关于直接将mySQLi数组转换为json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆