无法从SQLite数据库获取数据

时间:2019-05-27 17:51:53

标签: php sql sqlite pdo

我正在尝试运行以下查询:

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";

当找不到categorysearchterm时,则解析为:

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();

当找到searchtermcategory时,将返回记录。但是此代码中出现的任何其他情况都不会返回任何记录,即使它们在“用于SQLite的数据库浏览器”中运行时也会出现

编辑: 我尝试过硬编码

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 
      WHERE
        nfc_film.title LIKE '%k%' LIMIT 10 OFFSET 0

一无所获

1 个答案:

答案 0 :(得分:0)

您可能会发现,当您仅使用一个或另一个术语时,会得到错误,就像尝试绑定到不存在的变量一样。
(我认为)取决于您有条件地构建SQL的位置,您可能拥有:searchterm:category或两者都有-但您始终尝试将它们绑定到两者。

因此,如果有一个要绑定的值-然后分别绑定每个术语...

if(!empty($search_term)){
    $sqlGetFilms->bindParam(':searchterm', $sqlSearchTerm);
} 
if(!empty($category)) {
    $sqlGetFilms->bindParam(':category', $category);
}