直接将mySQLi数组转换为json数组

编程入门 行业动态 更新时间:2024-10-28 10:29:04
本文介绍了直接将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数组

本文发布于:2023-10-28 23:01:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   mySQLi   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!