Skip to content
Advertisement

PHP GET or POST data into variable including

Want to convert dynamic GET variables to two internal variables so that I can use these values in SQL query.

I am passing a variable string to a URL like this

http://localhost/api-data?serial=1923473
http://localhost/api-data?manufacturer=jaguar
http://localhost/api-data?location=london
http://localhost/api-data?country=uk

I want to convert the GET data into two different variables, for example serial becomes $data1 and 1923473 becomes $data2. GET data is always in above format I just want to convert into two different variables.

print_r($_GET);

I can see the variable is passed like an array. My question, if data passed in following format AAAAA=BBBBB as get variable, how do I convert AAAAA into variable $data1 and BBBBBB into £data2. Bear in mind GET data will always be unique.

Once I have this data in 2 unique variables, I want to run a SQL query.

select blah1, blah2, blah4, blah5 from datastore where $data1 = "$data2";

Thank you in advance.

Advertisement

Answer

$_GET is an array of all parameters passed. So, a URL of ?abc=def&foo=bar would result in a $_GET of

array(2) { 
    ["abc"]=> string(3) "def" 
    ["foo"]=> string(3) "bar" 
}

Using this, you can loop through each item and append it to a query:

foreach($_GET as $key => $val) {
    $query .= " AND $key = '$val'";
}

However, be sure you account for SQL injections. The best option for countering this in this scenario is to verify each key with a list of valid keys.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement