简体   繁体   中英

How to export one row selection to JSON using MySQLi and prepared statement

I am working on the below code. How can I export the result of one row in JSON?

I tried this like

$arr = [];
$arr = $stmt->get_result()->fetch();

but I am getting this error:

Uncaught Error: Call to undefined method mysqli_stmt::get_result()

$stmt = $mysqli -> prepare('SELECT id, name, email, phone FROM users WHERE id = ?');

$userId = 1; // or $_GET['userId'];

$stmt -> bind_param('i', $userId);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($id, $name, $email, $phone);
$stmt -> fetch();

You must be using a very old PHP version, probably PHP 5.3. I strongly recommend to upgrade to a recent version as soon as possible.

Once you have upgraded, you can use the following.

$stmt = $mysqli->prepare('SELECT id, name, email, phone FROM users WHERE id = ?');
$userId = 1; // or $_GET['userId'];
$stmt->bind_param('i', $userId);
$stmt->execute();
$json = json_encode($stmt->get_result()->fetch_assoc());

I found a useful example in the php documentation here: https://www.php.net/manual/en/mysqli-stmt.bind-result.php

Based on that example, here's what I recommend for you:

$results = array();
$stmt = $mysqli -> prepare('SELECT id, name, email, phone FROM users WHERE id = ?');
$userId = 1; // or $_GET['userId'];

$stmt -> bind_param('i', $userId);
$stmt -> execute();
$stmt -> bind_result($id, $name, $email, $phone);
while($stmt->fetch()){
    $results[] = array(
        "id"=>$id,
        "name"=>$name,
        "email"=>$email,
        "phone"=>$phone
    );
}
$stmt->close();
$output = json_encode($results);

Use PDO :

$db = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);

$sth = $db->prepare("SELECT id, name, email, phone FROM users WHERE id = ?");
$sth->execute([ $userId ]); // or $_GET['userId'];
$dbUser = $sth->fetch(PDO::FETCH_ASSOC);
echo json_encode($dbUser);

If you project is API use:

header('Access-Control-Allow-Origin: *'); // For CORS
header('Content-Type: application/json');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM