从PHP检索JSON数据

时间:2018-09-30 23:49:24

标签: php

如果我在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();
?>

1 个答案:

答案 0 :(得分:1)

如注释中所述,由于代码易受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