zhuanzhou
zhuanzhou

Reputation: 2443

put the value as an argument of a function?

supposed a variable named $xlnum value is as this 20,4,56,987,68,96.....the variable $xlnum value is input by the vistor.

the next i will passed the value to a sql query. if the value is one. that i can know how to do it. eg:

$result=mysql_query("select nid,title form node where nid=20");
while($row = mysql_fetch_object($result)) {
    echo $row->nid;
    echo $row->title;
}

but now the value is 20 4 56...,i want to loop out all the nid and title of 20,4,56,987,68,96.....how do i do.

Upvotes: 0

Views: 69

Answers (3)

Matthew
Matthew

Reputation: 48284

In short:

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

But you need to validate that it contains sane values.

Assume $xlnum = '20,4,56,987,68,96'; in these examples. Both end up with $sql that you can pass to mysql_query.

Option 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)";

Option 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)";

These are just two different ways to make sure the input is valid. The second is slightly different in that it will just ignore the pieces that are invalid.

I prefer something more like the second since it's easy to accidentally mess up a regular expression.

Upvotes: 0

Haim Evgi
Haim Evgi

Reputation: 125496

why not using WHERE ... IN

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

Upvotes: 2

fabio
fabio

Reputation: 2339

if $xlnum is an array you could do something like this:

$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;
}

If $xlnum is really just a string with comma separated numbers then just put the $xlnum inside the () without imploding.

Upvotes: 1

Related Questions