3 回答

TA貢獻1869條經驗 獲得超4個贊
您必須使用非常舊的 PHP 版本,可能是 PHP 5.3。我強烈建議盡快升級到最新版本。
升級后,您可以使用以下內容。
$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());

TA貢獻2051條經驗 獲得超10個贊
我在這里的 php 文檔中找到了一個有用的示例:https ://www.php.net/manual/en/mysqli-stmt.bind-result.php
基于該示例,這是我為您推薦的內容:
$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);

TA貢獻1797條經驗 獲得超6個贊
使用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);
如果您的項目API使用:
header('Access-Control-Allow-Origin: *'); // For CORS
header('Content-Type: application/json');
- 3 回答
- 0 關注
- 131 瀏覽
添加回答
舉報