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
Edited to add code
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.
Related
I'm getting null values after I run the DBEscape($data) function that is for SQL injection protection. Can someone help?
My inputs are all multiple arrays, ex: name="quote[][dt_flight]", name="quote[][acft]", etc.
Method is POST.
function DBEscape($data){
$link = DBConect();
if(!is_array($data)){
$data = mysqli_real_escape_string($link,$data);
}
else {
$arr = $data;
foreach ($arr as $key => $value){
$key = mysqli_real_escape_string($link, $key);
$value = mysqli_real_escape_string($link, $value);
$data[$key] = $value;
}
}
DBClose($link);
return $data;
}
function DBCreate($table, array $data, $insertId = false){
$table = DB_PREFIX.'_'.$table;
$data = DBEscape($data);
var_dump($data);
$fields = implode(", ", array_keys($data));
$values = "'".implode("', '", $data)."'";
$query = "INSERT INTO {$table} ({$fields}) VALUES ({$values});";
var_dump($query);
return DBExecute($query, $insertId);
}
if(isset($_POST["quote"]) && is_array($_POST["quote"])){
foreach($_POST["quote"]["dt_flight"] as $key => $text_field){
$last_id = DBCreate('quote',$_POST['quote'],true);
$i++;
}
}
The connection works since it is inserting the rows into the tables. I used vardump before and after the DBEscape to figure out that it is deleting the values, the keys are fine.
PS: The proposed answer is for a single variable not an array.
As you can see in your var_dump-result, the data you sent to DBCreate and thus to DBEscape looks like
array(
'dt_flight' => array(0 => '2018-06-13'),
'acft' => array(0 => 'VQ-BFD',
// and so on
)
Therfore the data you sent to
// $value = array(0 => '2018-06-13') here
$value = mysqli_real_escape_string($link, $value);
And well, mysqli_real_escape_string doesn't like arrays very much, thus will return NULL and thus inserting empty data in your table.
You most likely want to resolve this error within your foreach($_POST["quote"]["dt_flight"]) loop, since I suppose you sent multiple flight-data:
foreach($_POST["quote"]["dt_flight"] as $key => $text_field) {
// $key would be 0, for $_POST["quote"]["dt_flight"][0] = '2018-06-13'
$keyData = [];
foreach($_POST["quote"] as $field => $allFieldValues) {
// Walk over every field, and add the value for the same $key
if (is_array($data) && isset($allFieldValues[$key])) {
// Would add for example $keyData['acft'] = $_POST['quote']['acft'][0] = 'VQ-BFD';
$keyData[$field] = $allFieldValues[$key];
}
}
var_dump($keyData);
// Would look like array(
// 'dt-flight' => '2018-06-13',
// 'acft' => 'VQ-BFD',
// and so on
// )
$last_id = DBCreate('quote',$keyData,true);
$i++;
}
Although this is not part of your question, I really suggest you also take care of my comment on your question about mysqli_real_escape_string not being a safe way to escape column-names (or table-names and so on). For example with following solution:
function DBCreate($table, array $data, $insertId = false) {
// For each table the known columns
$columns = array( 'quote' => array('dt_flight', 'acft', '...') );
// Verify valid table given
if (!isset($columns[$table])) {
throw new InvalidArgumentException('No such table: ' . $table);
}
// Remove everything from data where the key is not in $columns[$table]
// = Remove everything where the column-name is non-existing or even an attempt to hack your system
$data = array_intersect_key($data, array_fill_keys($columns[$table], null));
if (!count($data)) {
throw new InvalidArgumentException('No (valid) data given at all');
}
// Next, continue with your implementation
}
I'm attempting to update a nested array in php. However, my updates have no effect. Here's the relevant code:
foreach($form["fields"] as $field){
Populate Checkbox Fields
if($field['type'] == 'checkbox'){
$inputs = $field['inputs'];
$count = '0';
foreach($inputs as $input){
if(($user_meta[$input['id']] !== '') && (isset($user_meta[$input['id']]))){
$select = true;
}
else{
$select = false;
}
$field['choices'][$count] = array( 'text' => $field['choices'][$count]['text'], 'value' => $field['choices'][$count]['value'] , 'isSelected' => $select );
$count = $count + '1';
}
}
}
I've tried a few different workarounds after searching for this error, but none of them seem effective. I'm grateful for any help anyone can offer.
Just use a reference & for $field with your existing code:
foreach($form['fields'] as &$field){
Alternately, use the key and modify the main array:
foreach($form['fields'] as $key => $field){
// later in the code
$form['fields'][$key]['choices'][$count] = array( /* ... */ );
I am trying to use codeigniter's active record class to fetch a value from the database that i need to insert to a table with this code
$q = $this->db->get('center_number');
$cd = $this->db->get('running_tasks');`
$ask_for_permission = array(
'messagefrom' => $le_message_from,
'messageto' => foreach ($q->result() as $row)
{
$row->center_number;
},
'messagetext' => 'The dataset'. '' .foreach ($cd->result() as $row)
{
$row->task_name;
}. ' is requesting permission to credit the account.Reply with yes to allow or no to decline.Anything else other than yes or no shall be ignored.'
);
I get the error:
unexpected 'foreach'
How can I fetch the record from the database from within $ask_for_permission array?.
// First Generate the Array
$ask_for_permission = array(
'messagefrom' => $le_message_from,
'messageto' => '',
'messagetext' => 'The dataset'. '' .foreach ($cd->result() as $row)
{
$row->task_name;
}. ' is requesting permission to credit the account.Reply with yes to allow or no to
decline.Anything else other than yes or no shall be ignored.'
);
// Second, populate it with all values of the $q->result() array
foreach ($q->result() as $row)
{
$ask_for_permission['messageto'] .= $row->center_number;
}
Try this
function msgTo() {
$str = '' ;
foreach ($r->result() as $row) {
$str .= $row;
}
return $str;
}
and replace your foreach with msgTo()
I solved it this way
$q = $this->db->get('center_number');
$le_message_from = '08009898';
$ask_for_permission = array(
'messagefrom' => $le_message_from,
'messageto' => $q->row->center_number,
'messagetext' => 'The dataset'. ' '. $this->db->query("select task_name from running_tasks limit 1")->row()->task_name .' '.'is requesting permission to credit the account.Reply with yes to allow or no to
decline.Anything else other than yes or no shall be ignored.'
);
$this->db->insert('messageout', $ask_for_permission);
I have the following code,
This is where i process the textfield input type wherein i type in the ingredient of an recipe.
The proper format of how one should input the ingredient is like this.
5-ml milk, 4-ml water, 2-pcs carrot
There are always delimiter in between since i have different columns for quantity, unit of measurement and the name.
I have no problem with the separation. I have another table. Which is named ingredients.
This is where i populate different ingredients like milk and put in what food group they belong and their nutritional info(what it gives off, like calcium).
Anyhow, I get a database error, Somehow, when i try to insert after all that processing, both the type and nutrition are null. I've thought about it, maybe my query was wrong? but it didnt give off any warning or notice. Though it only gave me notice/warning that both the values are undefined when i tried to declare them at array $comp which are the values to be inserted.
I get this error,
Error Number: 1048
Column 'nutrition' cannot be null
INSERT INTO component (componentname, quantity, unit,
nutrition, type) VALUES ('milk', '5', 'ml', NULL, NULL)
Filename: C:\www\KG\system\database\DB_driver.php
Line Number: 330
The code:
function insertrecipe()
{
$ingredients = $this->input->post('ingredients');
$recipename = $this->input->post('recipename');
$recipe = array(
'recipename' => $recipename,
'description' => $this->input->post('description'),
'instruction' => $this->input->post('instructions'),
'serving' => $this->input->post('serving'),
);
$this->db->insert('recipe', $recipe);
$this->ingredient($ingredients,$recipename);
}
function ingredient($ingredients,$recipename)
{
$ids = array();
$first_slice = explode(',',$ingredients);
$secondslice = $this->second_slice($first_slice);
foreach($secondslice as $qty => $iname)
{
$arr = explode('-',$qty);
$third_slice[$arr[1]] = $arr[0];
$sql = $this->db
->select('nutrition,group')
->where('ingname', $iname)
->from('ingredients')
->get()
->result_array();
$result = $this->db->query($sql);
foreach($result->result_array() as $row)
{
$ingredient_type = $this->get_ingredient_type($row['group']);
}
foreach($third_slice as $measure => $num)
{
$comp = array(
'componentname' => $iname,
'quantity' => $num,
'unit' => $measure,
'nutrition' => $nutri,
'type' => $ingredient_type
);
if($insert2 = $this->db->insert('component',$comp))
{
$latest_id = $this->db->insert_id();
$ids[] = $latest_id;
}
}
}
}
function second_slice($data)
{
foreach($data as $key => $value)
{
$ingredient = explode(' ', trim($value));
$second_slice[$ingredient[0]] = $ingredient[1];
}
return $second_slice;
}
function get_ingredient_type($data)
{
//foreach($data->result_array() as $row)
//{
if($data['group'] == "vegetable")
{
$type = 1;
}
else if($data['group'] == "fruit")
{
$type = 2;
}
else if($data['group'] == "dairy")
{
$type = 3;
}
else if($data['group'] == "seafood")
{
$type = 4;
}
else
{
$type = 5;
}
//}
return $type;
}
The database table of component has the following columns.
componentid componentname quantity unit nutrition type
nutrition is varchar unit is int. I guess they're not null or cols that dont accept null values.
I've separated different foreach loops into functions. I originally thought the error was because i had 3-5 for each loop within that function alone. so i decided to separate them into functions.
I have the following code
while($row = $usafisRSP->fetch_assoc()) {
$id = $row['id'];
$Applicantid = $row['Applicantid'];
$unique_num = $row['unique_num'];
// .................
$hidden_fields = array($Applicantid, $unique_num, $regs_t ....);
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
}
and the result is something like this
0 = 116153840
1 = 136676636
2 = 2010-12-17T04:12:37.077
3 = XQ376
4 = MUKANTABANA
I would like to replace 0, 1, 2, 3 etc with some custom values like "Id", "application name" to make the result like
id = 116153840
application name = 136676636
etc ..
how can I do that ?
Replace the $hidden_fields = array(... line with the following:
$hidden_keys = array('id', 'Applicantid', 'unique_num');
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
If you want to suppress all fields with value 0, either use
$hidden_fields = array_filter($hidden_fields, function($v) {return $v != 0;});
(this will completely omit the 0-entries) or
$hidden_fields = array_map($hidden_fields, function($v) {return ($v==0?'':$v);});
(this will leave them blank). If you're using an older version than 5.3, you'll have to replace the anonymous functions with calls to create_function.
I assume not every field in your row should be a hidden field. Otherwise you could just do $hidden_fields = $row.
I would create an array that specifies the hidden fields:
$HIDDEN = array(
'id' => 'Id',
'Applicantid' => 'application name',
'unique_num' => 'whatever'
);
And then in your while loop:
while(($row = $usafisRSP->fetch_assoc())){
$hidden_fields = array();
foreach$($HIDDEN as $field=>$name) {
$hidden_fields[$name] = $row[$field];
}
//...
foreach($hidden_fields as $name => $value) {
$hidden_fields[$name] = $name . ' = ' . base64_decode($value);
echo $hidden_values[$name];
// or just echo $name, ' = ',$hidden_fields[$value];
}
}
foreach ($row as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
This could give you something relevant. Through accessing the string keys from the row array which contains the string keys