我有以下PHP脚本生成MySQL查询并运行它,但是当前查询返回空结果。
$sth = $dbh->prepare("SELECT TeamID FROM UserTeam WHERE UserID=? AND Deleted IS NULL");
$sth->execute(array($_POST['userID']));
$teams = $sth->fetchAll();
$sql = "SELECT * FROM Event WHERE UserID=? AND Deleted IS NULL";
if (count($teams) > 0) {
$sql .= " OR TeamID IN (";
foreach ($teams as $team){
$sql .= $team['TeamID'] . ",";
}
$sql = substr($sql, 0, -1);
$sql .= ")";
}
$sql .= " ORDER BY Created DESC LIMIT ?, 10 ";
$sth = $dbh->prepare($sql);
$sth->execute(array($_POST['userID'], $_POST['start']));
$events = $sth->fetchAll();
$response["success"] = 1;
$response["result"] = $events;
$response["sql"] = $sql;
$response["post"] = $_POST;
echo json_encode($response);
例如给出输出JSON数组:
{
"post" : {
"start" : "0",
"userID" : "33"
},
"result" : [
],
"sql" : "SELECT * FROM Event WHERE UserID=? AND Deleted IS NULL OR TeamID IN (12,13,17) ORDER BY Created DESC LIMIT ?, 10 ",
"success" : 1
}
但是,如果我手动对数据库运行生成的查询(用正确的值替换?),我会得到预期的结果(返回10个结果)
更新
甚至将SQL生成更改为硬编码值而不是?我仍然没有结果。
即
{
"post" : {
"start" : "0",
"userID" : "33"
},
"result" : [
],
"sql" : "SELECT * FROM Event WHERE UserID=33 AND Deleted IS NULL OR TeamID IN (12,13,17) ORDER BY Created DESC LIMIT 0, 10 ",
"success" : 1
}
答案 0 :(得分:0)
尝试在sql查询中添加括号。例如,而不是:
SELECT * FROM Event WHERE UserID=33 AND Deleted IS NULL OR TeamID IN (12,13,17) ORDER BY Created DESC LIMIT 0, 10
尝试:
SELECT * FROM Event WHERE UserID=33 AND (Deleted IS NULL OR TeamID IN (12,13,17)) ORDER BY Created DESC LIMIT 0, 10
答案 1 :(得分:0)
您无法在LIMIT
子句中使用占位符。您也不需要,因为它是一个易于安全的整数。此外,您可以从第一个查询中获取列,以便更轻松地构建第二个列。我怀疑这可以通过单个查询获取,但在没有看到您的数据库架构的情况下无法确定。
最后,您没有从数据库代码中捕获任何错误,因此您无法知道是否有任何成功。假设您正确设置了连接,您应该能够捕获任何异常。
<?php
try {
$sth = $dbh->prepare("SELECT TeamID FROM UserTeam WHERE UserID=? AND Deleted IS NULL");
$sth->execute([$_POST["userID"]]);
$teams = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (PDOException $e) {
// do something here
}
$start = (int)$_POST["start"];
$sql = "SELECT * FROM Event WHERE UserID=? AND Deleted IS NULL";
if (count($teams) > 0) {
$sql .= " OR TeamID IN (" . implode(",", $teams) . ")";
}
$sql .= " ORDER BY Created DESC LIMIT $start, 10";
try {
$sth = $dbh->prepare($sql);
$sth->execute([$_POST["userID"]]);
$events = $sth->fetchAll();
} catch (PDOException $e) {
// do something here
}
$response["success"] = 1;
$response["result"] = $events;
$response["sql"] = $sql;
$response["post"] = $_POST;
header("Content-Type: application/json");
echo json_encode($response);