View Full Version : Use variable as ID and request table from MySQL?

09-19-2011, 06:30 PM
Hello, I have been able to turn a multiple select option form into a php array in this form:


$aVenues = $_POST['select3'];

echo("<p>You didn't select any venues!</p>\n");
$nVenues = count($aVenues);

echo("<p>You selected $nVenues venues: ");
for($i=0; $i < $nVenues; $i++)
echo($aVenues[$i] . " ");


$aVenues is the individual numbers received from the form and $nVenues is the number of those received.

Basically, what you get with this code is this:

You selected 2 venues: 2 6

The numbers 2 and 6 are id's sent from the form, and I would like to use these numbers to request the ID of a row in a database and make a simple table. How would I go about doing that?

My Mysql is basic and all I came up with is this:

$sql = "SELECT * FROM some_database WHERE id IN ($aVenues)";

Thanks everyone :)))

Old Pedant
09-19-2011, 07:09 PM
Assuming that the id's are indeed numbers, then your code is correct.

You just need to ensure that the PHP variable $aVenues contains a comma-delimited list of the numbers.

That is, you would want the equivalent of

$aVenues = "2, 6";

Since it would appear to me (a non-PHP person) that $aVenues is actually an array, all you need to do is convert the array to the delimited string.

Again, not a PHP person, but...

So probably:

$sql = "SELECT * FROM some_database WHERE id IN (" . implode(",",$aVenues) . ")";


09-19-2011, 09:19 PM
You are the best, thanks!

09-20-2011, 05:09 PM
I'm not sure if using the implode would be the best idea from a security approach unless you first check the array to make sure it only contains numbers not say SQL. And if you are going to iterate over the array to check it you could build the string at the same time.

Old Pedant
09-20-2011, 08:50 PM
Good point, though you could easily do something like this:

$list = implode(",", $aVenues);
if ( preg_match("\'", $list) > 0 )
... an attempt to do SQL injection ...
... abort ...

Only works for lists of numbers, of course.

Not sure I have the "\'" right for the preg_match, but you get the idea.