Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically set variables php, design pattern

Tags:

php

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 the identical script except rather than car, truck or the table autos I will be working with another table, different variables and possibly more or less variables. Is there a way or a good design pattern to use such that I only have to write one instance of this script vice the 15 or so I might otherwise have to write.

like image 222
WildBill Avatar asked Oct 09 '22 03:10

WildBill


2 Answers

This has security implications when combined with less than perfect code, but I'll assume that's not an issue for you.

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

A benefit of using extract is you get to specify the behavior when name collisions would occur. You might consider the EXTR_PREFIX_ALL flag though.

Or, just make a white list, which is best imo.

$allowed = array('car', 'count');
$vars = array_intersect_key($_GET, array_flip($allowed));
extract($vars);
like image 142
goat Avatar answered Oct 13 '22 01:10

goat


You can dynamically set variables like that:

$string = 'varName';
$$string = 'Hello World'; // $$string is $varName
echo $varName; // returns 'Hello World'
like image 26
js-coder Avatar answered Oct 13 '22 01:10

js-coder