How can retrieve values in update mode using smarty (PHP)? - php

I want to make email template management.I have a column additional_data where I'm inserting two input fields values (Subject and Body.)
Subject value contain simple text and body value contain HTML and other templates related materials.
My PHP Code
$additional_data = array();
// getting data again for update to fill up form
$editdata = ($id && $display == 'Update') ? $db->getRow("SELECT * FROM `{$db_table}` WHERE `nli_id`='$id'") : FALSE;
if(!is_array($editdata['additional_data']) && count($editdata['additional_data']))
$additional_data = json_decode($editdata['additional_data'], TRUE);
p($additional_data, 'Additional Data');
// setting template vars
if(count($additional_data))
{
foreach($additional_data as $key => $value)
{
$tmpl->setvar($key, $value);
} // foreach ends
unset($key);
unset($value);
} // if ends
HTML Code
<input type="text" class="span6" autocomplete="off" name="subject" id="subject" value="{var name='additional_data'}">
<textarea name="body" class="span6 autogrow">{var name='additional_data'}</textarea>
So let me know where I am wrong or is there any other way to solve the problem.

Yes, this "smarty" looks very strange. I would say it's Vlib:
http://en.wikipedia.org/wiki/VlibTemplate
But anyway, in you PHP code you are going trough $additional_data array and creating variables from elements of that array. Element key is name of new template variable and element value is tmpl. variable value.
So, in your template code "additional_data" does not exist. Print out that $additional_data array from your PHP code to see what elements are you really passing to template engine.

Related

Create variables from unknown number of fields in PHP

I have a dynamic form that has the following field.
<input class="uk-input" id="Employer1Name" name="EmployerName[]" type="text" placeholder="">
The user can add as many as they need using a button which increments the id dynamically to keep them unique, for example:
<input class="uk-input" id="Employer1Name" name="EmployerName[]" type="text" placeholder="">
<input class="uk-input" id="Employer2Name" name="EmployerName[]" type="text" placeholder="">
<input class="uk-input" id="Employer3Name" name="EmployerName[]" type="text" placeholder="">
I won't know how many they include but I need to take this into PHP and get it into a table. I use JQuery Serialize and Ajax to get the data to the PHP script. Do I create a new variable for each item? If so how? I have:
foreach($_POST['EmployerName'] as $key => $value) {
echo $key." - ".$value;
}
This loops over all 'EmployerName' to get the key and value but I need to then process these into a MySQL statement into a database. I just don't know how to go about getting the data out of the loop, I am thinking of creating variables for each such as $EmployerName.$key = $value, but I get stuck with "Undefined variable: EmployerName in ..."
*edit
I can use $value to get the value but how do I associate that with a variable to use later?
There is much more data so doing anything in the loop will cause issues with other variables being looped over that only occur once.
I agree with #Nathanael, the correct way to associate the value with a new variable would be
${'EmployerName'.$key} = $value
But the values are already accessible with $_POST['EmployerName'][$i] where $i is the index, and you can get the total values count with count($_POST['EmployerName'])
If you want to store your data for later use you can do the following:
<?php
$newArray = array();
foreach($_POST['EmployerName'] as $key => $value) {
$newArray[$key] = $value;
}
die('<pre>' . print_r($newArray, true) . '</pre>');
Of course you can build your $newArray they way you need. For example with the other data you mentioned. Make sure you handle the user input and use PDO for your database operations later on.
Let me know if you have any other question
Working example: https://ideone.com/qPcG80

run a code block in php foreach even when foreach array is empty

I have a dynamic form which does insert and update at the same time. This is working well for updating existing data but it is not working when inserting data, that is because $input_fields is empty so the foreach throws an error and form fields won't show. so how do I run the code inside the foreach when $input_fields is empty?
<?php foreach ($input_fields as $input_field) : ?>
// some demo code below
<div class="form-group">
<label for="">Name</label>
<input class="form-control field_name_input name" type="text" name="data[][name]" value="<?= $input_field['name'] ?>">
</div>
// some demo code below ends
<?php endforeach; ?>
I tried below code before foreach
if(!$input_fields) {
$input_fields = [];
};
and below code in foreach
foreach ((array)$input_fields as $input_field)
but that doesn't help as first code snippet is just empty array so the loop won't happen and second one is almost same thing. I hope you understand.
EDIT 1: $input_fields is an array where I saved form attributes.
Instead of an empty default array use a default entry:
if(!is_array($input_fields) || empty($input_fields)) {
$input_fields = [
[
'name' => "Hubba Bubba"
// and some more elements
]
];
};
Your if doesn't work because you are asking if the array is empty and then assigning it empty.
Instead of doing that you could surround your foreach loop inside the if that checks if it is empty
Then it will only run if size >=1
If you want to run the loop at least once you could and empty default value or you could write the html tags inside your if block
so, I added this lines of code before foreach and It's working as I
expected
if(empty($input_fields)) {
$input_fields = [[]];
};

PHP Form variable and data to & from text file?

I have a form with quite a lot of input fields and checkboxes.
When I submit the form I want to write the form field name and value to a text file.
<input type="text" name="mailHost" value=""/>
<input type="text" name="mailUser" value=""/>
<input type="text" name="mailPass" value=""/>
So with this as an example it would be written to a file as :
mailHost = VALUE
mailUser = VALUE
mailPass = VALUE
For a few form fields it fine doing each on by hand, but is there a function or way to do this for numerous fields ?
And then the same for reading it back ?
Again using the same example above I'd end up with the following when read back :
$mailHost = Value, $mailUser = value etc where the variable name is dynamically created and the value assigned ?
Thanks
You can iterate through your $_POST array:
foreach ($_POST as $key => $value) {
file_put_contents('file.txt', $key . " = " . $value . "\n", FILE_APPEND);
}
NOTE
Unchecked checkboxes will not in the $_POST array.

get input from html form in PHP by iterations

I am creating a webpage which display a form with 16 questions, each row of input looks like:
<li>*question 1*</li>
<input type="text" name="answer1" style="height: 40px;" size="50" dir="rtl">
<li>*question 2*</li>
<input type="text" name="answer2" style="height: 40px;" size="50" dir="rtl">
and so on - i have 16 (html) lines like that
(by the way, is there a way to prevent this code duplication? this code smells...) and in the end a 'submit' button.
my php script should receive these answers, and put every answer in a variable called "answer(i)" e.g I can write 16 lines of this kind:
if (isset($_POST['submit'])) {
$answer1 = $_POST['answer1'];
$answer2 = $_POST['answer2'];
...ect.
...
}
this (also) feels like a lot of code duplication. is there a way to make it more general and efficient so that if i'm looking to add some new question I won't have to goo through all this again?
I am new to PHP and HTML, and I though of declaring some functions and call them everytime but when I googled keywords like 'html functions' etc. I didn't find and helping info.
edit: The answers labels maybe different than 'answer1, answer2...' and can be a set of different words ('age', 'gender'...)
For the HTML use something like this:
$questions = array(
'question1',
'question2',
//...
);
foreach($question as $id => $qText){
?>
<li>
<?php echo $qText ?>
<input type="text" name="answers[]" style="height: 40px;" size="50" dir="rtl">
</li>
<?php
}
On PHP side you would have your answers in $_POST['answers'], it would be an array. And believe me, if you want to put this values from array into separate variables, it is a red flag: something wrong with your code. You do not want to have a set of answers as independent variables.
You could run a loop to go through the POST array and extract the information into another array.
foreach ($_POST as $k => $v) {
$$k = $v;
}
That will put all of the $_POST data into PHP variables named the same as the form fields generating them (beware you will also get a $submit as well from the button triggering the form).
Is this what you are looking for?
foreach (range(0,16) as $i)
{
${'answer'.$i} = $_POST['answer'.$i];
}
or use extract(), If you apply on your $_POST, keys in your $_POST variable gets assigned as variable.
Here is official documentation.

Getting post value from 2 input with the same name

First of all, I can't change the name of my input.
I have tried naming the inputs with an array like this:
<select name="info[]" class="select-block" id="2">
But then the css doesn't work.
So, how can I get post from 2 input with the same name with php
<select name="info" class="select-block" id="2">
<select name="info" class="select-block" id="1">
Just use a class or ID or something else for CSS and set up your input names using array notation. I would worry about how your form functions first. Make that work correctly and then worry about CSS, not the other way around.
In CSS if you have select[name=info] then replace it with .select-block and use info[] for name
Quick'n'dirty way, just to show that it is possible.
$qs = file_get_contents('php://input');
$_POST = array();
foreach(explode('&', $qs) as $varval){
list($var, $val) = explode('=', $varval, 2);
if (isset($_POST[$var])) {
if (!is_array($_POST[$var])) {
$_POST[$var] = array($_POST[$var]);
}
$_POST[$var][] = $val;
} else {
$_POST[$var] = $val;
}
}
This need some polishing like urldecoding. Of course it also comes with limitations: when form is sent with enctype multipart (for uploading files) php://input is not available. Also this does not care about arrays, so if you have some form element with name like info[], it wouldn't be parsed correctly. It also can be corrected but personally I would change my HTML/CSS

Categories