This doesn't work but should give an idea of what I am trying to do.
SELECT id FROM table WHERE var IN ($arr)
Thanks,
Chris
>Using IN can I use an actual php array?
>
>SELECT id FROM table WHERE var IN ($arr)
Have a look at the PHP implode() function. You can list the array items
as a string with a comma as item separator, which is what you want.
--
Erick
Really nothing to do with mysql, so added alt.php.
//Example for numbers:
$query = "SELECT id FROM table WHERE var IN (".implode(',', $arr).")";
//Example for strings:
$query = "SELECT id FROM table WHERE var IN ('".implode("','", $arr)."')";
--
//Aho
It will not work because MySQL has no idea how a PHP-array looks like
So, you should write some PHP-code to 'translate' the array into
something that MYSQL understands, and that confirms to what you are
trying to get with the statement above...
--
Luuk
Thanks all!
Hadn't thought of implode.
Chris
Looks like a good recipe for sql injection attacks.
Although the mysql_query function will only execute one statement per
call, there's still the opportunity for undermining the behaviour of
the query.
This is safer:
function array_to_mysql_in($cur,$next)
{
$cur.=$cur ? ',' : '';
return $cur . "'" . mysql_real_escape_string($next) . "'";
}
$query = "SELECT id FROM table WHERE var IN (".array_reduce
($arr,'array_to_mysql_in').")";
C.
Not to mention that the code will also fail with a value such as "O'Brian".
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstu...@attglobal.net
==================
I think (not tested) a prepared statement & bind parameters might
prevent both...
regards,
M.
Ah yes, but try preparing statements and binding parameters where the
query consists of
WHERE x IN (var1, var2, var3... uncertain number of vars)
which is the format of the OP's query. The best you can do (I welcome
corrections, though), is to create a parameter of the SET type and pass
that in. However, though you'd get points for sneakiness (twas the good
Captain P suggested this one a while back), you do have to keep an eye
out for the upper limit of how many values the SET type can hold.
Taliesin Nuin.
That's one option - but that wasn't the question, was it?