MySQL PHP - SELECT WHERE id = array()? [英] MySQL PHP - SELECT WHERE id = array()?

查看:45
本文介绍了MySQL PHP - SELECT WHERE id = array()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
使用数组的 MySQL 查询
将数组传递给 mysql

我在 PHP 中有一个数组:

I have an array in PHP:

$array = array(1, 4, 5, 7);

如您所见,我有一个包含不同值的数组,但我想编写一个 MYSQL 语句来检查 id 是否等于数组中的值.例如,如果一行的 id 为 1,它将返回该行,对于 4、5 和 7 也是如此.数组的长度可能因程序的性质而异,所以这就是问题所在.我可以这样做吗:

As you can see, I have an array of different values, but I want to write a MYSQL statement that will check if the id is equal to any of the values in the array. For example, if a row has an id of 1, it will return that row, the same for 4, 5, and 7. The length of the array can vary due to the nature of the program, so that's where the problem is. Could I just do:

SELECT ...
  FROM ...
 WHERE id = '$array'

或者有更好的方法吗?
如果我不清楚,请向我询问更多信息.

Or is there a better way?
If I was unclear, please ask me for more info.

推荐答案

使用IN.

$sql = 'SELECT * 
          FROM `table` 
         WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

这篇关于MySQL PHP - SELECT WHERE id = array()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆