PHP Variable Variables don't work... Why? - php

I'm using a function that returns a Fetched Array from a Database ( PDO::fetch(PDO::FETCH_ASSOC) ).
this function returns A LOT OF COLUMNS and when I am editing all those columns in a Form, obviously I need the fields to be populate with the current data.
Code (modified for the question):
//returns something like $owner["name"], $owner["lastname"],
//$owner["phone1"] ... and 53 fields more.
$owner = controllerGetOnwer($ownerID);
//So I used a foreach to create VARIABLE VARIABLES
foreach($owner as $key=>$value) {
${$key} = $value; //you get something like $name = <what is in that column>
}
I am gonna use this form in a lot of pages, not only for owners, but also for customers, administrators, and so on... That's why I decided to put the form in a function inside a static class I already used to 'render' all the HTML I will use a lot of times (such as Headers, logos, menus, etc)
//This is inside the HTMLRenderClass
renderTheEditForm() {
?>
<form>
Name: *<br/>
<input type="text" name="personalname" value="<?php if(isset($name)) echo $name; ?>"/><br/><br/>
Last Name: *<br/>
<input type="text" name="personallastname" value="<?php if(isset($lastname)) echo $lastname; ?>"/><br/><br/>
Phone Number 1:<br/>
<input type="text" name="personalphone1" value="<?php if(isset($phone1)) echo $phone1; ?>"/><br/><br/>
<!-- AND 53 FIELDS MORE -->
</form>
<?PHP
}
All the variables that you see inside the VALUE attribute are the same as the ones that are being created dinamically in the FOREACH. When I paste the form HTML code below the Foreach, I can see the data being loaded, but when I use the Function from the HTMLRenderClass I get nothing... I haven't been able to find the reason.
I hope I explained well, thanks beforehand!

It appears that you need to define your variables inside the function or pass them into the function.

Related

using a variable name inside another variable name

I'm sorry for my English.
I have a dynamic php form connected to mysql DB. In stock array I save the mysql query results. I can access the name of the product[0] and its available quantity [4]. I use the name of the product[0] to set input name and available quantity to fix max parameter value, as it below:
<input type="number" name="<?php echo $stock[$i][0]?>" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em>
I don't kwow how many inputs will be created (and which, because it is dynamic), so I save the name of the input created in another array $_SESSION["INPUTS"] as show:
array_push($_SESSION["inputs"],$stock[$i][0]);
In the next page, I want to $REQUEST the value from the inputs. Now I have the problem, I need to call $REQUEST for the created inputs which names are saved inside $_SESSION["inputs"], I need something as:` $REQUEST["$_SESSION["inputs"]]. I try it different ways without exit.
Any idea? Any alternative?
thanks
I think the best approach is by naming the input name attribute like an array: eg: "name=stock[the product name]". This approach allows you to discard the usage of the $_SESSION["inputs"].
<input type="number" name="stock[<?php echo $stock[$i][0];?>]" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em">
Then to read the values:
$stocks = $_REQUEST['stock'];
foreach($stocks as $productName => $quantity) {
//...
}
This works because the inputs are converted to a php array after being submitted.
You can even get the number of inputs by calling count:
echo count($_REQUEST['stock']);

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.

CakePHP: Form helper with saveMany() to edit multiple rows at once

In my view (/View/Tests/admin_edit.ctp) I want to edit multiple rows (from a different model) by pointing the form to the QsetsController and the "admin_order" action then use the saveMany($this->request->data) to update all changes.
/View/Tests/admin_edit.ctp:
echo $this->Form->create( 'Qset', array('action'=>'order', 'admin'=>1));
$n = 1;
foreach ($qsets as $qset) : ?>
<h3>Question set <?php echo $n; $n++;?></h3>
<?php echo $this->Form->input('Qset.'.$n.'.order'); ?>
<?php echo $this->Form->input('Qset.'.$n.'.id', array('type'=>'hidden') ); ?>
...
$n++;
endforeach;
echo $this->Form->end('save');
/Controller/QsetsController.php
public function admin_order() {
$data = $this->request->data; //maybe just $this->data ?
$this->Qset->saveAll($data);
$this->Session->setFlash( "Order saved.");
$this->redirect( Controller::referer() );
}
Currently, my data does not get saved (although there are no errors).
Also, only the first input echoed by the foreach loop appears with a correct order field value. Each subsequent one has no value at all.
Update:
I changed $n = 1 to $n = 0 and now the first AND second input appear with their correct order values.
update2:
The markup for the form starts like this:
<form action="/admin/qsets/order" id="QsetOrderForm" method="post" accept-charset="utf-8">
The markup for the input fields which appear correct:
<div class="input number"><label for="Qset2Order">Order</label>
<input name="data[Qset][2][order]" type="number" value="3" id="Qset2Order">
</div>
The markup that results for the empty input fields:
<div class="input number"><label for="Qset3Order">Order</label>
<input name="data[Qset][3][order]" type="number" id="Qset3Order">
</div>
Update3:
I solved the problem with the inputs not displaying correctly! Notice I was incrementing $n before echoing the the inputs, so this was creating duplicates at the end of the loop. I moved $n++ to after the inputs and now they appear correctly. Phew. Now I just need to get them to save.
Useful references:
Cake book chapter on saveMany()/saveAll()
Similar question
You reference the manual but probably haven't read it well enough :)
Quoting from the section for saveMany():
Note that we are passing numerical indices instead of usual $data
containing the Article key. When saving multiple records of same model
the records arrays should be just numerically indexed without the
model key.
So instead of $data pass $data['Qset'] to saveAll()/saveMany().
Also Controller::referer() is not a static method use $this->referer()

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

PHP: Parsing of a given form input variable

How would I go about parsing incoming form data where the name changes based on section of site like:
<input type="radio" name="Motorola section" value="Ask a question">
where 'Motorola section may be that, or Verizon section, or Blackberry section, etc.
I do not have any control over changing the existing forms unfortunately, so must find a way to work with what is there.
Basically, I need to be able to grab both the name="" data as well as its coresponding value="" data to be able to populate the email that gets sent properly.
Well, you don't receive a HTML form, but just field names and values in $_POST. So you have to look what to make out of that.
Get the known and fixed fields from $_POST and unset() those you've got [to simplify]. Then iterate over the rest. If " section" is the only constant, then watch out for that:
foreach ($_POST as $key=>$value) {
if (stristr($key, "section")) {
$section = $value;
$section_name = $key;
}
}
If there are multiple sections (you didn't say), then build an section=>value array instead.
<form action="formpage.php" method="post">
<input type="radio" name="Motorola_section" value="Ask a question">
</form>
$motorola = $_POST['Motorola_section'];
if ($motorola =='Ask a question')
{
form submit code if motorola is selected
}
Well, first off, you shouldn't have spaces in the name field (even though it should work with them).
Assuming it's a form, you can get the value through the $_POST (for the POST method) and $_GET (for the GET method) variables.
<?php
if ( isset( $_POST['Motorola section'] ) ) // checks if it's set
{
$motoSec = $_POST['Motorola section']; // grab the variable
echo $motoSec; // display it
}
?>
You can also check the variables using print_r( $_GET ) or print_r( $_POST ).

Categories