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.
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);
You can dynamically set variables like that:
$string = 'varName';
$$string = 'Hello World'; // $$string is $varName
echo $varName; // returns 'Hello World'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With