把值作为函数的参数?

时间:2011-06-12 05:41:27

标签: php mysql

假设一个名为$xlnum的变量值为20,4,56,987,68,96.....变量$ xlnum值由vistor输入。

接下来我将该值传递给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...,我想循环出20,4,56,987,68,96.....的所有nid和标题。

3 个答案:

答案 0 :(得分:2)

为什么不使用WHERE ... IN

where nid in (2,3,4.....)

答案 1 :(得分:1)

如果$ 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放在()内而不会发生爆炸。

答案 2 :(得分:0)

简而言之:

$result = mysql_query("select nid,title form node where nid IN ($xlnum)");

但你需要验证它包含合理的值。

在这些示例中假设$xlnum = '20,4,56,987,68,96';。两者都以$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)";

这些只是确保输入有效的两种不同方法。第二个略有不同,因为它只会忽略无效的部分。

我更喜欢第二种类似的东西,因为很容易意外搞乱正则表达式。