从bind_result返回json对象

时间:2017-01-23 22:35:20

标签: php

我有简单的PHP脚本,它返回我的用户对象,看起来像这样

<?php
require_once '../dbConnect.php';
session_start();

if (empty($_SESSION["id"])) {
    http_response_code(401);
    return;
}

    $stmt = $mysqli->prepare("SELECT id, firstName, lastName, email FROM users WHERE id = ?");
    $stmt->bind_param("i", $_SESSION["id"]);
    $stmt->execute();
    $stmt->bind_result($id, $firstName, $lastName, $email);
    $stmt->fetch();

    $member['id'] = $id;
    $member['firstName'] = $firstName;
    $member['lastName'] = $lastName;
    $member['email'] = $email;

    echo json_encode($member);

    $stmt->close();
    $mysqli->close();;

?>

我的问题:有没有比这更好的方法来返回json对象,我需要用每个属性创建对象,这种东西是否有更“自动”的东西?

$member['id'] = $id;
$member['firstName'] = $firstName;
$member['lastName'] = $lastName;
$member['email'] = $email;
echo json_encode($member);

我问这个是因为我有这样写的相同脚本,但由于性能和安全性,我将其更改为准备好的语句

<?php
require_once '../dbConnect.php';
session_start();

if (empty($_SESSION["id"])) {
    http_response_code(401);
    return;
}

$memberId = $_SESSION["id"];
$query="SELECT id, firstName, lastName, email FROM users WHERE id='$memberId'";

$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$member = mysqli_fetch_assoc($result);

echo json_encode($member);

$mysqli->close();

?> 

我用的只是

$member = mysqli_fetch_assoc($result);

echo json_encode($member);

1 个答案:

答案 0 :(得分:1)

如果您有MYSQLND驱动程序,则可以将fetch_assoc()与预准备语句一起使用。

$stmt = $mysqli->prepare("SELECT id, firstName, lastName, email FROM users WHERE id = ?");
$stmt->bind_param("i", $_SESSION["id"]);
$stmt->execute();
$result = $stmt->get_result();
$member = $result->fetch_assoc();

如果没有,您可以直接在bind_result()中引用数组元素,而不是使用单独的变量。

$member = array();
$stmt->bind_result($member['id'], $member['firstName'], $member['lastName'], $member['email']);