伙计们,我正在尝试为uni项目提供网络服务。一切似乎都没问题,直到我运行代码并获得此错误未捕获错误:在null上调用成员函数fetchAll()。这是代码可以有人请告诉我它有什么问题吗?
<?php
header("Content-type: application/json");
$conn = new PDO("mysql:host=localhost;dbname=user;", "user", "pass");
$loc = $_GET["location"];
$type = $_GET["type"];
if(isset($_GET["location"]) && isset($_GET["type"]))
{
$result = $conn->query("Select * from resit_accommodation where location='$loc' and type='$type'")
}
else if (isset($_GET["location"]))
{
$result = $conn->query("Select * from resit_accommodation where location='$loc'");
}
else if (isset($_GET["type"]))
{
$result = $conn->query("Select * from resit_accommodation where location='$type'");
}
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
?>
答案 0 :(得分:3)
如果未设置任何$_GET
参数,则永远不会将$result
设置为任何内容,因此如果您尝试使用它,则会出现错误。
您还应该使用预准备语句而不是替换变量,以防止SQL注入。
<?php
header("Content-type: application/json");
$conn = new PDO("mysql:host=localhost;dbname=user;", "user", "pass");
$stmt = null;
if(isset($_GET["location"]) && isset($_GET["type"]))
{
$stmt = $conn->prepare("Select * from resit_accommodation where location= :loc and type= :type");
$stmt->execute(['loc' => $_GET['location'], 'type' => $_GET['type']]);
}
elseif (isset($_GET["location"]))
{
$stmt = $conn->prepare("Select * from resit_accommodation where location= :loc");
$stmt->execute(['loc' => $_GET['location']]);
}
elseif (isset($_GET["type"]))
{
$stmt = $conn->prepare("Select * from resit_accommodation where location= :type");
$stmt->execute(['type' => $_GET['type']]);
}
if ($stmt) {
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$rows = [];
}
echo json_encode($rows);
?>