我有这种结构的数据库

Id      Country         Interests
12      Azerbaijan      Acting,Reading
14      Azerbaijan      Reading,Writing
16      Azerbaijan      Acting,sleeping


而这个PHP / MYSQL

$Interests = "Acting,Reading";

$Country = "Azerbaijan";
$query = "SELECT * FROM user_opt WHERE Country='$country' AND Interests='$Interests' ";
$i = substr_count($Interests,',');
for($j = 0; $j <= $i; $j++) {
   $a = explode(',', $Interests);
   $query2 = "SELECT * FROM user_opt WHERE Country='$country' AND Interests LIKE '%{$a[$j]}%'";
}


因此,使用此代码,它返回了我这个ID

12
12
16
12
14


但我要它回来
12
16
14

最佳答案

您可能想使用OR来找到您的所有兴趣。为此,请先构建您的OR语句,然后将其插入查询中。注意:这不是安全/首选的方式!确保您正在使用PDO或mysqli并绑定您的参数!

$interestArr = [];
foreach($Interests as $Interest) {
    $interestArr[] = "Interests LIKE '%{$Interest}%'";
}

$query2 = "SELECT * FROM user_opt WHERE Country='$country' AND (".implode(' OR ',$interestArr).")";

关于php - MYSQL喜欢但不相等,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38229712/

10-12 06:00