我是PDO
的新手,我正在努力在准备好的声明中使用'where'语句。以下是我试过的代码。它返回无法从数据库中检索数据。
谁能告诉我这是什么问题?有什么可尝试的吗?
欣赏它!
$user_id = 1;
try {
$query = $db->prepare("
SELECT title, img, id
FROM listings
ORDER BY id DESC
WHERE userID = :user_id
LIMIT 2");
$query->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$query->execute();
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
$data = $query->fetchAll( PDO::FETCH_ASSOC);
return $data;
更新:我换了order
& where
子句,但它仍然不返回任何内容(与先前的错误消息相反)。
答案 0 :(得分:4)
像这样重写您的查询。 [您需要在WHERE ]之后放置ORDER BY子句
$query = $db->prepare("
SELECT title, img, id
FROM listings
WHERE userID = :user_id
ORDER BY id DESC
LIMIT 2");
答案 1 :(得分:1)
ORDER BY id DESC
需要在where
条件之后添加。
$query = $db->prepare("
SELECT title, img, id
FROM listings
WHERE userID = :user_id
ORDER BY id DESC
LIMIT 2");
Mysql Generic Select语法:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
答案 2 :(得分:0)
where子句应该在order子句之前 试试这个
$query = $db->prepare("
SELECT title, img, id
FROM listings
WHERE userID = :user_id
ORDER BY id DESC
LIMIT 2");