Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...