Reputation: 2443
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
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
.
// 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)";
$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
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