如何在“where”子句中使用多个值?

时间:2014-09-09 19:42:42

标签: php mysql

我的代码和我的数据库如下

$my=mysql_query("select * from users where email='ids'")or die(mysql_error);


id___email___________pass
1    abc@d.com        123
2    xxx@x.uk         333
3    ah@cc.com        555

我需要一个sintax,我会选择* where id ='1,3',当我回复$ row [email]时它会返回

abc@d.com
ah@cc.com

找到正确的语法

$all=mysql_query("select * from users where id IN ('1','2','3')");
while($row = mysql_fetch_assoc($all))
{
   echo $row['name'];
}

2 个答案:

答案 0 :(得分:4)

使用IN子句获取多封电子邮件的记录。

$my=mysql_query("select * from users where email IN ('$email','$email2','$email3')")
or die(mysql_error);

答案 1 :(得分:0)

另一个非理想的解决方案是向"其中"添加几个选项。子句。

使用更多资源,但有时也是您需要的资源。

顺便说一句,我强烈建议先将SQL放入变量中。

$myquery  = "select * from users ";
$myquery .= "where (1 = 0) "; // defaults to false
$myquery .= "or  (email='$email') "; // maybe true
$myquery .= "or  (email='$email2') "; // maybe true
$myquery .= "or  (email='$email3') "; // maybe true

$mydataset = mysql_query($myquery) or die(mysql_error);

有多个"或"表达式为" ="字符串比较,是非最优的,使用的资源更多,相当于" in"操作

然而,有时知道或使用这种等价物是有用的。如果您不确定源字符串是否区分大小写,或者您想要修剪不需要的空格的值,您还可以替换" ="运营商由"喜欢"操作

$email  = trim($email);
$email2 = trim($email2);
$email3 = trim($email3);

$myquery  = "select * from users ";
$myquery .= "where (1 = 0) "; // defaults to false
$myquery .= "or  (email like '%$email%') "; // maybe true
$myquery .= "or  (email like '%$email2%') "; // maybe true
$myquery .= "or  (email like '%$email3%') "; // maybe true

$mydataset = mysql_query($myquery) or die(mysql_error);

干杯。

相关问题