查找多个值,其中一个条件在一列mysql中

时间:2016-12-08 09:13:03

标签: php mysql

这是我的个人资料表:

<table border="1">
<tr>
<td>Name</td>
<td>Skills</td>
</tr>
<tr>
<td>John Doe</td>
<td>php-development, css, html, ajax</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>xml, jquery, ajax, php-development</td>
</tr>
<tr>
<td>Markinson Zuckerberg</td>
<td>html, php-development, ajax, magento</td>
</tr>
</table>

我正在尝试使用SQL中的get方法进行过滤:

<pre>$sql= "SELECT distinct * FROM `profile` WHERE status='1'";

if(isset($_GET['services']) && $_GET['services']!="") :
    $sql.=" AND services LIKE '%".implode("%','%",$_GET['services'])."%'";
endif;</pre>

我尝试了上面的代码进行过滤,但它正在将连接的SQL查询作为

SELECT distinct * 
FROM profile 
WHERE status='1' 
AND services LIKE '%affiliate-marketing%','%ajax%' 
ORDER BY pid DESC

任何解决方案?

1 个答案:

答案 0 :(得分:2)

您无法使用LIKE '%something%', '%somethingelse%',该语法无效。您需要使用OR关键字列出过滤的可能性。

假设$_GET['services']是一个数组:

<?php

$_GET['services'] = array('affiliate-marketing', 'ajax');
$sql = ''; // just for output purposes

$services_like = array() ;
foreach ($_GET['services'] as $service) {
    $services_like[] = ' service LIKE "%' . $service . '%" ';
}
$services_like_string = implode (' OR ', $services_like);

$sql .= 'AND ( ' . $services_like_string . ' ) ';

echo $sql; // echoes : AND ( service LIKE "%affiliate-marketing%" OR service LIKE "%ajax%" ) 
?>