Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

php - mySQLi array directly to json array

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

I mean.. avoid making a while loop

I have this:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...