基于数组的查询php

时间:2013-11-07 17:15:53

标签: php mysql

而不是一次在mysql数据库中搜索一个变量,我想搜索一些变量,并将其放入初始查询字符串

所以而不是

$query="SELECT * FROM table1 WHERE state = 'CA' OR state = 'CO' OR state = 'TX'";

我想要

$states = ("CA,CO,TX");
$query="SELECT * FROM table1 WHERE state = $states";

我试过了

<?
include("connect.php"); // file to connect to db
$states = array(CA,TX);
$states_str = implode(",", $states);


$query="SELECT * FROM table1 WHERE state IN ($states_str)";

$result=mysql_query ($query);
while($row = mysql_fetch_array($result)) {
echo $row['state'];
}

?>

但我收到此错误消息

 Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in  ... on line 11

这是第11行

while($row = mysql_fetch_array($result)) {

但是,如果我使用此代码,我得到一个结果,只是为了表明当我切换回旧的传统查询时它可以工作

<?
include("connect.php"); // file to connect to db
$states = array(CA,TX);
$states_str = implode(",", $states);


$query="SELECT * FROM table1 WHERE state = 'CA'";

$result=mysql_query ($query);
while($row = mysql_fetch_array($result)) {
echo $row['state'];
}

?>

然后我绕过了implode()的东西,我在其他地方找到了它,但它不适合我

3 个答案:

答案 0 :(得分:2)

显然,查询失败,因为没有引用字符串值。

尝试:

$states = array('CA','TX');
$states_str = implode("','", $states);
$query="SELECT * FROM table1 WHERE state IN ('$states_str')";

答案 1 :(得分:0)

<?
include("connect.php"); // file to connect to db
$states = array('CA','TX');
$states_str = implode("','", $states);
$states_str = rtrim($states_str,",'");


$query="SELECT * FROM table1 WHERE state IN ('$states_str')";

$result=mysql_query ($query);
if($result){
while($row = mysql_fetch_array($result)) {
echo $row['state'];
}
}
?>

那是因为你的查询失败所以先检查它

答案 2 :(得分:0)

 <?php
 include('../testi.inc');

 $states = array('CA','TX');
 $states_str = implode("','", $states);

 $query = "SELECT * FROM states WHERE state IN ('$states_str')";

 $result=mysqli_query ($db,$query) or die(mysql_error());
 while($row = mysqli_fetch_assoc($result)) {
 echo $row['state'];
 }

 ?>

或类似的东西