在php中选择WHERE子句

时间:2012-03-26 22:48:29

标签: php mysql

我正在尝试制作一个测验应用程序,我需要从数据库中检索“n”个问题。我还需要使用类别或难度过滤器来过滤结果。

如果用户选择类别(例如),我没有任何问题:

$size = $_POST['param0'];
$category = $_POST['param1'];

$stmt = $db->prepare("SELECT *
                      FROM questions_fr
                      WHERE categories = :categories
                      LIMIT 0, $size");

$stmt->bindparam(":category", $category);
$stmt->execute();

但如果他想要所有类别怎么办?

我可以做一些类似的事情,只在我的php文件中生成一个查询吗?

$stmt = $db->prepare("SELECT *
                      FROM questions_fr
                      WHERE categories = * (here, select all the categories)
                      LIMIT 0, $size");

或者我应该做这样的事情?

(pseudocode)
if ($category != "all_categories")
{
    $stmt = $db->prepare("SELECT *
                          FROM questions_fr
                          WHERE categories = :categories
                          LIMIT 0, $size");
}
else if ($category == "all_categories")
{
    $stmt = $db->prepare("SELECT *
                          FROM questions_fr
                          LIMIT 0, $size");
}

2 个答案:

答案 0 :(得分:2)

如果他们选择“所有类别”,则将类别变量设置为通配符并使用LIKE子句。

if ($category == "all_categories") {
    $category = '%';
}

...

SELECT *
FROM questions_fr
WHERE categories LIKE :categories
LIMIT 0, $size

答案 1 :(得分:1)

添加另一个参数。

SELECT *
  FROM questions_fr
  WHERE categories = :categories
    OR 1 = :all_categories
  LIMIT 0, $size

如果您想要所有类别,请将其作为1传递。

相关问题