php - 从 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();
?>
解决方案
正如评论中提到的,由于您的代码对 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
推荐阅读
- python - Strava REST API | swagger-client 不返回完整的DetailedAthelete reperesentation
- javascript - 在数组中映射数组
- javascript - Vue - 将数组作为参数传递
- c# - 为什么在 .NET 5 中指定循环枚举值时枚举的顺序很重要?
- php - 用户/浏览器是否可以看到服务器端的 PHP curl 请求
- python - 如何将列表分隔到不同的表格并将表格打印到reportlab中的各个页面pdf?
- node.js - Type-graphql,Mikoorm 查询返回 Ref
而不是用户 - docker - 本地主机窗口 10 中的 Docker 连接被拒绝
- javascript - Javascript地图问题返回一个空值的数组
- java - 如何使用共享主键保持一对一休眠