首页 > 解决方案 > 从 PHP 中检索 JSON 数据

问题描述

如果我在 URL 中传递 ID,则以下查询不会根据 ID 检索数据。如何根据 ID 检索 JSON 数据?

<?php
$servername = "localhost";
$username = "testphp";
$password = "1234";
$dbname = "testphp";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "select * from test where id =? order by count asc";
$result = $conn->query($sql);
$arr=array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       array_push($arr, $row);
    }
    echo json_encode($arr);
} else {
    echo "0 results";
}
$conn->close();
?>

标签: php

解决方案


正如评论中提到的,由于您的代码对 SQL 注入的脆弱性,您必须像这样更改您的代码。

$sql = "select * from test where id = ? order by count asc";
$result = $conn->query($sql);

$sql = $conn->prepare("select * from test where id = ? order by count asc");
$sql->bind_param("i", $_GET["id"]);
$result = $conn->query($sql);

我假设列id是一个数字/整数字段。有关参数绑定的更多信息 - http://php.net/manual/en/mysqli-stmt.bind-param.php


推荐阅读