How to dynamically set php variables, design pattern

I have several php scripts that have the following structures:

$count = $_GET['count'];
$sort = $_GET['sort'];
$car = $_GET['car'];
$driver = $_GET['driver'];

...

$SQL = "SELECT car, truck FROM autos WHERE car='$car' AND truck='truck'";

...

Another script will be identical to the script except for the car, truck, or table. I will work with another table, with different variables and, possibly, with more or less variables. Is there a way or a good design template to use, so I need to write only one instance of this script of vice version 15 or so, which I could write.

+5
source share
3 answers

This has security implications combined with less than perfect code, but I assume this is not a problem for you.

extract($_GET, EXTR_SKIP);
echo $car;

extract , . EXTR_PREFIX_ALL.

, imo.

$allowed = array('car', 'count');
$vars = array_intersect_key($_GET, array_flip($allowed));
extract($vars);
+2

:

$string = 'varName';
$$string = 'Hello World'; // $$string is $varName
echo $varName; // returns 'Hello World'
+1

You can do it,

foreach(array('count','car','driver', 'sort') as $v){
    $$v = $_GET[$v]
}

Or

foreach($_GET as $k => $v){
    $$k = $v
}

Later can also be achieved by including register_globals in php.ini. But it is dangerous .

+1
source

All Articles