将数组传递给mysql [英] Passing an array to mysql

查看:204
本文介绍了将数组传递给mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个值数组(business_id)

I currently have an array of values (business_id's)

让它说

Array
(
[0] => 12
[1] => 14
[2] => 15
)

使用这些值中的每一个从数据库中获取每个business_id的关联行信息的最佳方法是什么.

What is the best way to use each of these value to get the associated row information for each business_id from the database.

这是我的问题吗?显然,您可以做到

Can it be one in one query is my question. Obviously, you could do

$q = "select * from business where business_id = 12";
$rs = mysql_query($q);

推荐答案

$ids = array(1, 2, 3, 4);

$ids = join(', ', $ids);
$query = "SELECT * FROM business WHERE business_id IN ($ids)";
// $query => SELECT * FROM business WHERE business_id IN (1, 2, 3, 4)

通常的SQL注入警告仍然适用,您可能想先遍历id以进行验证或转义.另外,如果您希望使用字符串而不是数字,请使用以下命令:

The usual SQL injection warnings still apply, you may want to loop through the ids first to validate or escape them. Also, if you expect strings instead of numbers, use this:

$ids = array('a', 'b', 'c', 'd');

$ids = join("', '", $ids);
$query = "SELECT * FROM business WHERE business_id IN ('$ids')";
// $query => SELECT * FROM business WHERE business_id IN ('a', 'b', 'c', 'd')

这篇关于将数组传递给mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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