按一个或多个数组值查询表

时间:2012-04-18 16:22:07

标签: php mysql

我正在尝试运行查询以确定列A是否为true。如果为true,则获取不同列B的内容(可能的数组用“,”分隔)并使用这些内容查询不同的表。我的问题是,B列可能是一个数字,也可能是10个全部用“,”分隔的数字,我需要在第二个表中查询前一个查询的每个数字的列。如果有人可以提供帮助那就太棒了。

编辑:我尝试使用数组爆炸功能,但无法弄清楚如何查询下一个表以包含这些值。

我觉得它像是

query = select * from table where location = arrayValue[1] or location = arrayValue[2] 

2 个答案:

答案 0 :(得分:0)

使用PHP的explode()函数将字符串转换为数组。

<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);

//Build SQL query
$sql = "SELECT * FROM table WHERE ";
for($i=0; $i < count($bcolumnArray); $i++)
{
   $sql .= "location = " . $value;
   if($i != count($bcolumnArray)-1)
   {
      $sql .= " or ";
   }
}

//Query your second table here
mysql_query($sql);
?>

文档:http://php.net/manual/en/function.explode.php

答案 1 :(得分:0)

Telmo Marques在这里进行了改编,但改进了:

<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
array_walk($bcolumnArray, 'htmlentities');

//Build SQL query
$SQL = 'SELECT * FROM table';
if(count($bcolumnArray)){
    $SQL.= ' WHERE IN ("'.implode('", "', $vbcolumnArray).'")';
}

//Query your second table here
$Qry = mysql_query($sql);

// Results here :
while($Res = mysql_fetch_assoc($Qry)){
    print_r($Res);
}
?>

我会建议PDO ......看看:PDO

相关问题