This may be a stupid question but I'm lost here. I need to send array with some data in it to another PHP file using POST variable. This is my form:
<form action="test.php" method="post">
<label name="html[]" hidden><?php echo $array; ?></label>
<input type="submit" value="submit">
</form>
And this is test.php
<?php
$html = $_POST['html'];
for($i = 1; $i<=9; $i++){
echo $html[$i];
}
?>
So this is what I tried, but it's not displaying anything. please help
You need to create a number of input elements with the same name, each of which will have one array item as its value:
<?php foreach ($array as $item) : ?>
<input type="hidden" name="html[]" value="<?= htmlspecialchars($item); ?>" />
<?php endforeach; ?>
Important points to keep in mind:
$item must always be a scalar value (string, integer, etc). You cannot pass in arrays piecemeal with this technique.
Never forget that since you are injecting variables into HTML output you must escape and/or sanitize them properly. In this case this is done with htmlspecialchars, which must know about your output encoding to work correctly in general (look up its third parameter).
There is also an alternative approach that can be used to pass arrays piecemeal through serialization:
<input type="hidden" name="html"
value="<?= htmlspecialchars(serialize($array)); ?>" />
And you would then unserialize it on the receiving end:
$html = unserialize($_POST['html']);
I 'm mostly including this option for completeness, as in practice session variables are a much better way of passing complex state between requests.
Is it necessary to put the data of the array in a hidden field? You can store the array in $_SESSION and access it. Btw, I think you have a problem, labels can be submitted, in that case you must put the data into an input field with type="hidden".
Related
It was easy passing data from controller to view. Also, to pass data from view to controller you need form tags. But, how do you pass an array from an input form? any idea guys? here's what the array looks like:
$test = array
(
array($employee_id[0],$name[0],$days_worked[0],$overtime_hours[0]),
array($employee_id[1],$name[1],$days_worked[1],$overtime_hours[1]),
array($employee_id[2],$name[2],$days_worked[2],$overtime_hours[2])
);
and from my html view i got here an input form:
<input name="test" type="text" class="form-control" id="test" value="<?php echo $test;?>">
and when i got to my model to test if it gotten the data inside the array:
$this->test = $_POST['test'];
echo $test = $_POST['test'];
all i got was a String "Array". I can't access what's inside the array. I need help.
Your questions is unclear.. you want to pass the array to you view, or to the HTML output into the INPUT element?
These are 2 different things, as one is only passing an array internally in you application (on the server), and the second is passing it into you form data, displaying it in the browser, and then sending the form to the server and getting the data there.
For the first - i see no problem there, as passing variables is no issue
The second - it is not possible by default to pass a multi-dimensional array into a form input. Becasue the input has only 1 dimension.
You could pass the data with some conversion function e.g. as a JSON string
value="<?php echo json_encode($test);?>"
and then load it like this:
$this->test = json_decode($_POST['test']);
But that does not make sense in the frontend I guess, as the user would not understant what data is presented in the input field.
To to it in a logical way, I would divide the data into groups, and then display accordingly in more input fields e.g.
<input name="test[0][employee_id]" type="text" class="form-control" id="test" value="<?php echo $test[0][0];?>">
<input name="test[0][employee_name]" type="text" class="form-control" id="test" value="<?php echo $test[0][1];?>">
<input name="test[0][employee_days_worked]" type="text" class="form-control" id="test" value="<?php echo $test[0][2]?>">
<input name="test[0][employee_overtime]" type="text" class="form-control" id="test" value="<?php echo $test[0][3];?>">
but do it more nicely. This way you can create sth which will be sent as a multi-dim. array to the php script.
as suggested in another answer here, you can see the structure with var_dump($test)
Array values cant be passed in form data directly.
You should use json_encode.
In your view file
$encoded_text = echo json_encode($test);
<input name="test" type="text" class="form-control" id="test" value="<?php echo $encoded_text ;?>">
Now in your model just decode this
$test = json_decode($test, $assoc = TRUE);
If you use serialize() on your controller and unserialize() on the view you should be able to access it in the same way. I believe that's what you're asking.
Can you please help me in this context.
<form action="sample.php" method="post">
<input type="text" name="first[]" />
<input type="text" name="second[]" />
</form>
I am using this code in a loop and I need to get all the values in another page.
How can I get these value as array in another page.
you should be able to use $_POST array in the sample.php page
PHP's $_POST Array, taken from the docs:
An associative array of variables passed to the current script via the HTTP POST method.
first, add s submit button to your form, it should look like this:
<form action="sample.php" method="post">
<input type="text" name="first[]" />
<input type="text" name="second[]" />
<input type="submit">
</form>
and in sample.php:
<?php
print_r($_POST);
?>
This is the most simple example,
once you get the hang of it, I recommend you read the docs on topics such as:
htmlspecialchars
htmlspecialchars — Convert special characters to HTML entities
You can access it as array
$_POST['first'][0] // 0 will be index for single
to list all just loop
foreach($_POST['first'] as $first) {
...
}
Your values will end up in $_POST, and because you're using the [] syntax, you'll get an array. So, to get your first array, do:
$first = $_POST['first'];
You could then iterate over it like so:
foreach ($first as $item) {
...
}
I think this will help you.
$first=$_POST['first'];
$second=$_POST['second'];
foreach($first as $key=>$first){
echo 'Your first value'.$first.'Your second value'.$second[$key];
}
I currently have an HTML file, with a form in it, that when submitted POSTs the form & calls a simple short PHP file that calls a function within another PHP file using the POSTed variables as parameters. The files are both below. What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
Ideally, this would set the call to the function:
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
as the form action. Does anyone know how/if this can be achieved?
HTML:
<FORM ID="FORM1" METHOD="POST" AUTOCOMPLETE="off" ACTION = "writeToDL.php">
<INPUT TYPE="hidden" NAME="Date" STYLE="WIDTH:0px; " MAXLENGTH="8" TITLE="Enter Date" Value="<?php $dt = date('Y-m-d'); echo $dt ?>"/>
<INPUT TYPE="text" NAME="Time" STYLE="WIDTH:70px; " MAXLENGTH="7" ONCHANGE="validateTime();" />
<SELECT NAME = "Result">
<OPTION VALUE = OK></OPTION>
<OPTION VALUE = C>C</OPTION>
</SELECT>
<SELECT NAME = "Participant" STYLE = "WIDTH: 187">
<OPTION SELECTED VALUE = "">Select...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$val = $value->get_id();
echo "<OPTION VALUE='",$val,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
<TEXTAREA NAME='Notes' COLS='28' ROWS='5'></TEXTAREA>
<INPUT TYPE="image" SRC = "images/submit.png" VALUE="Submit Participant"/>
</FORM>
PHP File:
<?php
include_once('database/PE.php');
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
?>
You COULD do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include_once('database/PE.php');
insert_PE(new PE($_POST['Date'],$_POST['Participant'],$_POST['Time'],$_POST['Result'],$_POST['Notes']));
} ?>
<html>
... rest of your page here ...
</html>
That way the PHP code only fires if an POST was actually performed. Some would suggest checking for the presence of a form field, but that's unreliable - you might change the form down the road and forget to update the if(). Checking the request method is guaranteed to be 100% reliable.
What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
No. The client only knows about URIs.
A URI can map to a PHP program. Multiple URIs can map to the same PHP program. You can use logic to determine what functions to run for a given URI. You can't avoid having that logic in your program.
One option is to put method="_the_main_php_file_containing_function_to_be_called_"
I hope it works fine.
I think you could use a hidden field on the form, and populate it with the name of the function you want to run on "destination.php". Then a switch statement on "destination.php" could pull the name of the function from POST variable.
I got this and I have no idea what I'm missing here:
<?php
//Some validation for the SUBMIT form
if(isset($_POST['submit'])&&$_POST['submit']=='add'){
$_POST = array_map("mysql_real_escape_string", $_POST); //This little fella is responsible for the mess ¬¬
$campus_string = $_POST['campus']; //To get a checkboxes Array
....
print_r($campus_string); //to see if I am getting the checkboxes when submitting
}
?>
....
//Now inside <body> of the HTML
<form action="" method="post" name="filosofal">
//A little loop to create the checkboxes from a DB
foreach($campi as $keyCampi => $valueCampi){
echo '<tr>
<td>
<input type="checkbox" id="campus[]" name="campus[]" value="'.$value['Id'].','.$valueCampi['Id'].'" />'.$valueCampi['Nombre'].'<br />
</td>
</tr>';
}
</form>
But print_r doesn't show anything, the array is not being stored when submitting via POST. Hope you can help me to pinpoint where I'm screwing it.
EDIT: Solved
Well, I finally figured it out, it's kind of embarrasing.
In my code, I use:
$_POST = array_map("mysql_real_escape_string", $_POST);
to avoid some encoding conflicts (like names with 's on them), security and such.
I commented the line and it works now (didn't add that part since I wasn't aware its relevance on the issue), no changes needed to be done.
Don't know why it took me five days to find that little thing over there, but now is done. Anyways, thanks everyone.
Try adding
<input type="hidden" name="submit" value="add" />
Into your form, at the moment your if statement will be returning false...
Try dumping the post data:
echo "<pre>";
print_r($_POST);
//if you check the radio then it will be listed in your $_POST dump
//add action to your form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
foreach($campi as $keyCampi => $valueCampi){
?>
<tr>
<td>
<input type="checkbox" id="campus[]" name="campus[]" value="<?php echo $valueCampi['Id'].','.$valueCampi['Id']; ?>" /><?php echo $valueCampi['Nombre'].'<br />
</td>
</tr>';
<? php } ?>
</form>
Generally speaking, the way I see it is that checkbox is either ON or OFF. Therefore, in my mind, the name of the checkbox is the value. For instance:
<input type="checkbox" name="single"> Single?
If that checkbox is checked (value="on"), then the answer is yes. If it is not checked (value="off" or no value), then the answer is no. Therefore, my PHP code looks something like:
if ($_POST['single'] == 'on')
$single = true;
else
$single = false;
Basically, as far as I'm concerned, the "value" of a checkbox should never be set. That's my particular preference though, and it's worked well for me. It may not suit your needs, though.
Good luck.
i am trying to create a donate page. the hole page is php,
there is a textbox that hold the amount value which should be send via hidden input with the url to the the payment gateway. i have tryed many time but it is not working. i am still a beginner in this could any one please help me in fixing my code here
<div class="donate">
<?php
$amount = $_REQUEST['amount'];
$txtCurrency = 840;
$txtAmount = number_format($amount, 2, '.', '');
echo $amount;
$key = "TEST";
$txthttp = "http://test.com/you.php";
?>
<form action="payment.php" name="form1">
<input type="text" id="amount">
<input type="submit">
<input type="hidden" name="txtAmount" value="<?= $txtAmount; ?>">
<input type="hidden" name="txthttp" value="<?= $txthttp; ?>">
<input type="hidden" name="signature" value="<?= $key; ?>">
</form>
</div>
In general, you should avoid using $_REQUEST when you can use $_GET or $_POST. $_REQUEST allows variables to be set by either an HTTP GET or POST, which can pose a security risk, since your site will presumably use one or the other. With that said, here's what I would do:
Add method="post" to your form tag.
Access the input elements by looking at $_POST['txtAmount'], $_POST['txthttp'], etc.
In general, you can view all variables set in the POST by doing this:
var_dump($_POST);
You can access these values from payment.php with $_POST['txtAmount'], $_POST['txthttp'], $_POST['signature']. How you handle them will be up to your code. I see that you used the $_REQUEST array, which will work, however I believe it's better form to be specific and use the $_POST array.