sadssdsada sadssdsada - 1 year ago 62
MySQL Question

How to deal with more than three PHP GET Variables to Select data from MySQL database

I have a PHP page called

that has access to MySQL Database.
I use one table called:

In the table I have more than on row.
Every info has an
that I use to get the other info based on it:

$sql = "SELECT * FROM `MyTable` WHERE `id`='" . $_GET["var1"]'";
$result = $conn->query($sql);

So when I go to:


I get the other info like Name of the info by fetching the rows.

BUT I want to deal with more than one variable:


So I can get the info of every
and not one only.

I want to handle any number of variables and get it's data.

Thank you!

Answer Source

First, it would be easier to use an array for specifying multiple ids in the URL:


This way, in your PHP code $_GET['var'] will be an array and will contain all values specified in the URL.

Next, you have to make sure all array items (the ids) are numeric. There are many solutions for this, for example skipping non-numeric values:

// make sure parameters are OK
if (is_array($_GET['var'])) {
    // eliminate non-numeric values
    $ids = array_filter($_GET['var'], function($item) {
        return is_numeric($item);
else {
    // invalid arguments; throw exception or do something else

Finally, you have to use WHERE IN in your query (and verify of course if there are actually some values in the $ids array before executing the SQL query):

if (!empty($ids)) {
    $sql = "SELECT * FROM `MyTable` WHERE `id` IN (" . implode(",", $ids) . ")";
else {
    //TODO: no numeric ids specified, do something else...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download