问题描述
|
假设一个名为“ 0”的变量的值就是该“ 1”,则变量$ xlnum的值由访问者输入。
接下来,我会将值传递给sql查询。如果值为1。我可以知道该怎么做。例如:
$result=mysql_query(\"select nid,title form node where nid=20\");
while($row = mysql_fetch_object($result)) {
echo $row->nid;
echo $row->title;
}
但是现在的值是20 4 56...
,我想循环显示the1的所有图片和标题我该怎么办。
解决方法
简而言之:
$result = mysql_query(\"select nid,title form node where nid IN ($xlnum)\");
但是您需要验证它是否包含合理的值。
在这些例子中假设ѭ6。两者都以$sql
结尾,您可以将其传递给mysql_query
。
选项1
// remove white space
$xlnum = preg_replace(\'/\\s+/\',\'\',$xlnum);
// make sure the string is nothing but numbers separated by commas
if (!preg_match(\'/^(\\d+,)*\\d+$/\',$xlnum))
die(\"invalid format\");
$sql = \"select nid,title form node where nid IN ($xlnum)\";
选项2
$nids = array();
// loop through each comma delimited value
foreach (explode(\',\',$xlnum) as $nid)
{
// force the value to an integer
$nid = (int) $nid;
// if it is non-zero add it to the list
if ($nid) $nids[] = $nid;
}
// if the array is empty,nothing valid was entered
if (!$nids)
die(\"invalid format\");
// recreate the comma delimited string
$xlnum = implode(\',$nids);
$sql = \"select nid,title form node where nid IN ($xlnum)\";
这只是确保输入有效的两种不同方式。第二个稍有不同,因为它只会忽略无效的部分。
我更喜欢第二种,因为它很容易将正则表达式弄乱。
, 为什么不使用WHERE ... IN
where nid in (2,3,4.....)
, 如果$ xlnum是一个数组,则可以执行以下操作:
$result=mysql_query(\"select nid,title from node where nid in (\".implode(\',$xlnum).\")\");
while($row = mysql_fetch_object($result)) {
echo $row->nid;
echo $row->title;
}
如果$ xlnum实际上只是一个用逗号分隔的数字的字符串,则只需将$ xlnum放在()内而不会内爆。