I just joined a project developed in plain php ( As in no frameworks). I have a table that has 213 fields and according to the guidelines i have to do an isset, prepare string, prepare number for 212 fields.
This is a lot of repetitive code and most of the tables in this system are huge. As such i would like to save time by developing an isset generator but before I go re-inventing the wheel i would like to ask: Can anyone point me in the direction of such a generator that returns the isset code? Something similar to http://www.fpmgonline.com/mysql_insert.php
Supposing $data is my $_POST array , instead of checking many fields one by one I wanted to generate a bulk isset code
Here's is some sample code
<?php
$data = Array('name' => 'Sample name', 'desc' => 'Sample description');
if (isset($data['name'])) {
$name = trim($data['name']);
} else {
$return[] = ' Name code is required';
}
if (isset($data['desc'])) {
$desc = trim($data['desc']);
} else {
$return[] = ' Description is name is required';
}
if (isset($data['age'])) {
$age = trim($data['age']);
} else {
$age = 0;
}
?>
Thank you.
There is no need for "generating" code. That's why you have data structures, loops and conditionals in programming languages.
$data = Array('name' => 'Sample name', 'desc' => 'Sample description', 'age' => 'Foo bar');
$defaults = Array('age' => 0);
$messages = Array('name' => ' Name code is required', 'desc' => ' Description is name is required');
for($data as $key => $val) {
if (isset($data[$key])) {
$$key = trim($data[$key]);
} else if (isset($defaults[$key])) {
$$key = $defaults[$key];
} else {
$return[] = $messages[$key];
}
}
The need to use variable variables ($$key
) here also is plain wrong. When working with "dynamic" data you should not need to work with a separate variable for each item. I'd refactor that into this:
$clean_data = Array();
for($data as $key => $val) {
if (isset($data[$key])) {
$clean_data[$key] = trim($data[$key]);
} else if (isset($defaults[$key])) {
$clean_data[$key] = $defaults[$key];
} else {
$return[] = $messages[$key];
}
}
Also $data
should not be whatever comes from $_POST
. It should be everything that's in your fields list and then check if it's present in $_POST
, so that you don't end up running arbitrary code based on user input.
I did a simple one for the isset:
$data = Array('name' => 'Sample name', 'desc' => 'Sample description');
bulkisset($data, 'name,description,age');
function bulkisset($data, $table_fields) {
$code = '';
$inputs = explode(',', $table_fields);
foreach ($inputs as $key) {
$code .= '<br/>if (isset($data["' . $key . '"])){'
. '$name = trim($data["' . $key . '"]);} else {$' . $key . ' ="";};';
}
echo $code;
}
This might not be the best way to check data but with my hands tied I think this will save me some time.