下面显示的代码使用implode()执行mysql查询,在一个表达式中搜索多个变量,我喜欢:
<?
include("connect.php"); // file to connect to db
$states = array('CA','CO','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'];
}
?>
但我遇到了一个新问题。正如你从上面的“状态”中看到的那样是硬编码的。
我希望用户能够选择他们想要提取的状态,将该选择保存到数据库中的单独表中,然后将该列表读入上面显示的“状态”数组中。像这样:
<?
include("connect.php"); // file to connect to db
$sql_gs="SELECT states_c FROM states WHERE id='1'";
$result_gs=mysql_query($sql_gs);
$row_gs = mysql_fetch_row($result_gs);
$gcs = $row_gs[0];
$states = array($gcs);
$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'];
}
?>
但是此代码会抛出错误。
保存到上面提到的states表中的内容,以及states_c字段中包含的内容,VARCHAR字段是:
'CA','CO,'TX'
所以上面代码中的'$ gcs'变量......
echo $gcs; // result 'CA','CO,'TX'
换句话说,$ gca的文本(对于“获取选择状态”)与完全与上面硬编码版本中的文本相同
但是当我尝试放置$ gca变量的结果时,完全相同的文本,我得到一个错误,没有数据被拉,因为在这个声明中
$states = array($gcs); // $gcs reads exactly as 'CA','CO,'TX'
没有读取数据,而在这一个
中 $states = array('CA','CO,'TX');
状态被识别并且代码触发。
尝试通过命名变量在同一行代码中放置相同的文本而不是以硬编码的方式“拼写出来”会出现什么问题?
TIA
===================
更新
我试过了:
<?
include("connect.php"); // file to connect to db
$sql_gs="SELECT states_c FROM states WHERE id='1'";
$result_gs=mysql_query($sql_gs);
$row_gs = mysql_fetch_row($result_gs);
$gcs = $row_gs[0];
$states = explode("','", $gcs); // replaces $states = array('CA','CO','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['mail_state'];
}
?>
但仍然没有结果......
答案 0 :(得分:0)
使用爆炸。
$states = explode(",",$gcs);
嗯。看了你的内幕声明。你可能真的需要:
$states = explode("','",$gcs);