[英]SQL “LIKE” If empty returns all rows
Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. 您好,我有2个文本框,我想给用户选择一个选项以查找结果的选项。 The user can search through the id or the name.
用户可以搜索ID或名称。 My problem is because i use
LIKE%field%
when the user chooses to search through the id the name field stays empty and returns all the table rows. 我的问题是因为当用户选择搜索ID时,我使用
LIKE%field%
,名称字段保持为空并返回所有表行。 I want to have results only if the user enters some value in the textbox. 仅当用户在文本框中输入一些值时,我才希望得到结果。 This is my sql query.
这是我的SQL查询。 I'm using mysql
我正在使用mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all 谢谢你们
If the user has to select which field to search, you can do: 如果用户必须选择要搜索的字段,则可以执行以下操作:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself): 您可以在单个查询中执行此操作(从查询本身检查值):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation: 说明:
First condition: 第一个条件:
The query will select records with ID='$id'
only when $id
is not empty. 仅当
$id
不为空时 ,查询才会选择ID='$id'
记录。 If $id
is empty, query will not go for the second part ID='$id'
如果
$id
为空,则不会查询第二部分ID='$id'
Second condition: 第二个条件:
The query filters records with Name LIKE '%$name%'
only when $name
is not empty. 仅当
$name
不为空时,该查询才过滤具有Name LIKE '%$name%'
记录。 If $name
is empty, query will not go for Name LIKE '%$name%'
. 如果
$name
为空,则不会查询Name LIKE '%$name%'
。
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...else
s at php side. 注意:当您需要检查许多参数时,此技术非常有用,而不是在PHP端使用一堆
if...else
s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.