我正在尝试运行以下查询:
SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
FROM nfc_film
JOIN nfc_film_category
ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
ON nfc_film_category.category_id = nfc_category.category_id LIMIT 10 OFFSET 0
如果我将它放入“用于 SQLite 的数据库浏览器”中,这将起作用,返回正确的字段。
但是当试图在 PHP 中实现它时它不起作用:
$filmQuery = "
SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
FROM nfc_film
JOIN nfc_film_category
ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
ON nfc_film_category.category_id = nfc_category.category_id ";
if($search_term && $category){
$filmQuery .= "
WHERE
nfc_film.title LIKE :searchterm
AND
nfc_category.name = :category";
} else if ($search_term && !$category) {
$filmQuery .= "
WHERE
nfc_film.title LIKE :searchterm";
} else if (!$search_term && $category) {
$filmQuery .= "
WHERE
nfc_category.name = :category";
}
$filmQuery .= " LIMIT 10 OFFSET :page";
如果两者都没有category或searchterm没有找到,那么这将解析为:
SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
FROM nfc_film
JOIN nfc_film_category
ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
ON nfc_film_category.category_id = nfc_category.category_id LIMIT 10 OFFSET :page
然后我准备、绑定和执行查询:
$sqlGetFilms = $dbConn->prepare($filmQuery);
$sqlGetFilms->bindParam(':searchterm', $sqlSearchTerm);
$sqlGetFilms->bindParam(':category', $category);
$sqlGetFilms->bindParam(':page', $page);
$sqlGetFilms->execute();
$query = $sqlGetFilms->fetchAll();
当诺斯searchterm和category被发现,返回的记录。但是此代码中出现的任何其他情况都不会返回任何记录,即使它们在“DB Browser for SQLite”中运行时出现
呼如林