SQL / PHP如果不满足条件则选择所有内容

时间:2017-03-17 00:23:02

标签: php mysql sql

我的网页上有一个输入,有两个搜索参数(例如类型和位置)。输入参数后,PHP将搜索SQL数据库并输出满足输入参数的结果。

---
title: '1'
author: '1'
date: "March 16, 2017"
output:
  pdf_document: default
---

```{r cars}
library(pander)
pander(mtcars, split.cells = 5, split.table = Inf,
      caption = "A long long long long long long long long long long 
                 too long long long long long long long long caption")
```


```{r}
library(pander)
pander(mtcars, split.cells = 5, split.table = Inf,
      caption = paste("A long long long long long long long long long long", 
                 "too long long long long long long long long caption", 
                 collapse = "\n") )
```

但是,当用户只选择一个参数时,它应显示仅满足所选参数的所有结果。

类似的东西:

$sql = "
SELECT MainID
     , MainName
     , MainLocation
     , MainType 
  FROM Main 
 WHERE MainType = 'typeIWant' 
   AND MainLocation = 'LocationIWant' 
";

除非这不起作用。

无论MainLocation是什么,它都应显示满足MainType的所有结果。

这是怎么做到的?

2 个答案:

答案 0 :(得分:2)

以下行:

$sql = "SELECT MainID, MainName, MainLocation, MainType FROM Main WHERE MainType= 'typeIWant' AND MainLocation = '*' ";

正在搜索MainLocation被叫(或命名为)*

如果您只想搜索MainType,您应该这样做:

$sql = "SELECT MainID, MainName, MainLocation, MainType FROM Main WHERE MainType= 'typeIWant' ";

答案 1 :(得分:0)

您可以使用if statement来检查例如:

$sql = "
SELECT MainID
     , MainName
     , MainLocation
     , MainType 
  FROM Main 
 WHERE MainType = 'typeIWant'  
";

if (isset($_GET['MainLocation']) && $_GET['MainLocation'] != '') {
  $sql .= " AND MainLocation = 'LocationIWant'"
}