Passing an array to another page (Form) - php

I have the following array and form on page1.php:
$my_array = array("Volvo", "BMW", "Toyota");
echo " <form id=\"my_form\" action=\"page2.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"id\" value=\"10\">
<input type=\"hidden\" name=\"input_name\" value=\"".serialize($my_array)."\" />
Send </form>";
On the page2.php I want to print_r the array:
$id = $_POST['id'];
$passed_array = unserialize($_POST['input_name']);
print_r($passed_array);
Why I can't receive my_array on page2? I can't see the mistake I made!
PS: I received id on page2.

i'm glad #ksealey pointed out a more proper method of doing this, but for the sake of answering the question...the reason it's not working is that the serialize alone is not enough to prevent the invalid html. see result of what the serialize leaves in the html:
so you need to be sure the html you produce is valid. you might use encoding like base64 to produce safe html:
echo " <form id=\"my_form\" action=\"\" method=\"post\"";
echo "enctype=\"multipart/form-data\">";
echo "<input type=\"hidden\" name=\"id\" value=\"10\">";
echo "<input type=\"hidden\" name=\"input_name\" ";
echo "value=\"".base64_encode(serialize($my_array))."\" />";
then you can just add the decode to your output:
$passed_array = unserialize(base64_decode($_POST['input_name']));
print_r($passed_array);

If there is data to be passed from page to page use a session
<?php
//Page 1
session_start();
$value = 'Value from page 1';
$_SESSION['page_1_value'] = $value;
?>
<?php
//Page 2
session_start();
echo 'Value from page 1: '.$_SESSION['page_1_value'];
$_SESSION = array(); //If you want to wipe the session data after
OR, pass as value params that get cleaned, JSON object maybe?
<form id="my_form" action="page2.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="10">
<input type="hidden" name="input_name" value="<?php echo json_encode($my_array); ?>" />
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">Send</a
</form>
<?php
//Page 2
$object = json_decode(strip_tags(stripslashes($_POST['input_name'])));
var_dump($object);
I will say the first answer is safer.

This is the HTML that your first page is generating:
<input type="hidden" name="input_name" value="a:3:{i:0;s:5:" volvo";i:1;s:3:"bmw";i:2;s:6:"toyota";}"="">
One easy solution would be to replace your double quotes in
value=\"".serialize($my_array)."\"
with single quotes as so:
value='" . serialize($my_array) . "'
or you can escape the quotes in your serialized array as so:
value=\"". htmlspecialchars(serialize($my_array))."\"

I will just add my 2 cents in here :)
You may want to use a framework of some sort as this will ease the job for you a lot with situations like this (or similar). For example with Codeigniter framework you could have a form (view) that sends data to controller and in controller you could just grab the whole array as so:
$data = $this->input->post('array');
$data[0] should == 'Volvo'
So view:
<?php $my_array = array("Volvo", "BMW", "Toyota"); ?>
<form id="my_form" action="<?php echo site_url(controller_name/controller_function)" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="10">
<input type="hidden" name="input_name" value="".serialize($my_array)."" />
Controller:
public function foo() {
$data = $this->input->post('array');
for($i=0; $i<sizeof($data); $i++) {
echo $data[$i];
}
}

Related

Where can i implement a php code in joomla?

So I'm doing this website with Joomla and I don't have much experience with Joomla.
I just want to get the values of some checkboxes and print them into a text area.
I have the script already, I just need to implement it.
Here the raw Html code of the checkboxes:
<div class="checkboxShop">
<form action="" method="post">
<input type="checkbox" value="1" id="checkboxShopInput" name="shop" />
<label for="checkboxShopInput"></label>
</form>
</div>
And Here is the raw Html code of the submit button:
<form action="/Flex/index.php/shop" method="post">
<input type="submit" value="Buy">
</form>
All I want is to get all the values of the checkboxes and add them to a textarea in index.php/shop. I wrote this code to get the values but i don't know where to add this:
<?php
if(!empty($_POST['shop'])) {
foreach($_POST['shop'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
echo "<input type='text' name='message' value='" . $check . "'>"
}
}
?>
I've read that i need this but I'm not sure how: <?php include "name_of_script.php";?>
Thanks for the help

Why is my unserialize returning empty?

This could be a duplicate, but i couldn't find any one that helped.
I'm trying to pass an array of all the data to another page, throught the post method of a form. It looks like this:
<form method="post" action="../resource_load/export.php" target="_blank">
<input type="hidden" name="tipo" value="<?=$_GET['tipo']?>">
<input type='hidden' name='excel_array' value='<?php echo htmlentities(serialize($_SESSION['excel_array']))?>'>
<input type='submit' class='submit' id='btnExport' value='Export to Excel' />
So here i serialize the $_SESSION data. and this is what it looks like:
value="a:1:{s:12:"dpi_strategy";a:1:{s:5:"Plan1";a:1:{i:0;a:9:{i:0;s:3:"PCR";i:1;s:11:"Description";i:2;s:4:"Task";i:3;s:8:"Resource";i:4;s:13:"Baseline Plan";i:5;s:10:"Trend Date";i:6;s:4:"User";i:7;s:20:"Data Inicialização";i:8;s:6:"Status";}}}}
And here is where i unserialize:
$Excel_array = htmlentities(unserialize($_POST['excel_array']));
Yet, it returns null. Why is that?
If you do this, use htmlentities() to encode and html_entity_decode() to decode with raw values.
Secondly, I don't believe it is a good idea to output the data of serialize and unserialize user submitted data. The reason being is code injection that is a major security issue.
Instead, use json_encode() and json_decode().
Now because I see you have special chars in your array Data Inicialização you are indeed correct to convert those characters to another entity, but aslong if you have everything UTF-8 it will work.
<input type='hidden' name='excel_array' value='<?php echo json_encode($_SESSION['excel_array']) ?>'>
And:
# ../resource_load/export.php
var_dump(json_decode($_POST['excel_array']);
<?php
$temp = array();
$temp['aaa'] = "aaaaaaaaaaaaaaaaaaaaaaa";
$temp['bbb'] = "bbbbbbbbbbbbbbbbbbbbbbb";
$temp['ccc'] = "ccccccccccccccccccccccc";
$arr = array();
$arr['excel_array'] = $temp;
?>
<form method="post" action="">
<input type='hidden' name='excel_array' value='<?php echo htmlentities(serialize($arr['excel_array']))?>'>
<input type='submit' class='submit' id='btnExport' value='Export to Excel' />
</form>
<?php
if( isset($_POST['excel_array']) ) {
echo "<pre>";
$Excel_array = unserialize($_POST['excel_array']);
print_r($Excel_array);
}
?>
remove htmlentities from unserialize because you will unserialize an array and htmlentities use strings

Putting fetched array into <a href> value in PHP

I have a SQL query statement that will return a particular set of result. Such as ID, Names, Price. I have no problem with that.
However i am trying to add a link within the echo loop and set ID as the value so that i can post it to another page. Would that be possible ?
while ($row = mysql_fetch_array($result)) {
echo
"".$row{'Url'}."<br>";
echo
"Name:".$row{'Name'}."<br>";
echo
"Price: $ ".$row{'Price'}."<br>";
echo
'<div class = "qwerty" data-countdown= '.$row{'Time'}.'></div>';
echo
"Location:".$row{'Location'}."<br>";
echo
"Description:".$row{'Description'}."<br>";
echo ''.$row{'ID'}.'';
echo 'Show Comments
<form id="displayComments" style="display:none" target="jsScript()" method="post">
<input type="hidden" name="run" value=".$row{'ID'}." />
</form>';
You missed quotes. value="'.$row['ID'].'"
echo 'Show Comments
<form id="displayComments" style="display:none" target="jsScript()" method="post">
<input type="hidden" name="run" value="'.$row['ID'].'" />
</form>';
And php array use [ ]
http://ua2.php.net/manual/en/language.types.array.php

Insert Multiple data to mysql using a loop ...

so i have this code fragment here..
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question<?php echo $i; ?>' rows=3 cols=90></textarea></p>
<input type="radio" name="answer<?php echo $i; ?>" value="True"> True
<input type='radio' name="answer<?php echo $i; ?>" value="False"> False<br><br><br>
<?php
}
}
... i am making a quiz maker in php...
the first thing to do is to set up the desired number of questions, so the value entered will go on the $numTF variable. Depending on the entered value, the textarea part will be printed. and there will be different names for each text area. AND THE CODE ABOVE IS WHERE U PRINT THE FORMS AFTER U ENTER THE DESIRED VALUE.
The next thing is to save that in a database. since the name of each textarea will be based on a variable value($i) that is used in a loop (name="answer") , HOW CAN I USE IT IN $_POST??? Like, would i do it like this?? ($_POST['question']).
HOW CAN I SAVE THESE QUESTIONS IN A DATABASE??
PLEASE HELP ME ....
I WOULD BE SO MUCH MUCH MUCH GRATEFUL FOR A LIL HELP.
<?
var_dump($_POST);
?>
<form method="post">
<?
$numTF=4;
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question[<?php echo $i; ?>]' rows=3 cols=90></textarea></p>
<input type="radio" name="answer[<?php echo $i; ?>]" value="True"> True
<input type='radio' name="answer[<?php echo $i; ?>]" value="False"> False<br><br><br>
<?php
}
}
?>
<input type="submit" name="submit" value="submit"/>
</form>
Use $_POST['question'][1] // To get first question
Use $_POST['answer'][1] // To get first answer
Use loop to get all question and answers
I agree with Sachin as far as using name='question[]'. To answer question a little more as far as storing it in a database. Personally I would use a JSON array.
$store_answers = json_encode($_POST['answer']);
$store_questions = json_encode($_POST['question']);
Then just store $store_string in a TEXT field in your database. Then when you pull it back out of the database you can simple use:
$answers = json_decode($store_answers);
$questions = json_decode($store_questions);
Then you can loop through using a foreach like so:
foreach($questions as $key=>$question) {
echo "Question $key = {$answers[$key]} <br />";
}
This will display the results for each question.

Posting a variable that is unique to a row, how do I do this?

I am POSTING two things. The comment, which works ok, but the second item I need to post is the $list['id'] that is unique to this each row. How do I include this unique id, when the user clicks POST so that it can be used on the page that it is being posted to.
foreach ($posts as $key => $list){
echo " <tr valign='top'>\n";
echo " <tr>$list['id']
<div class='comment_text'>
<form method='post' action='add_comment.php'>
<textarea name='comment'</textarea>
<input class='btn' type='submit' value='Post'/>
</form>
</div>
</td>\n";
echo "</tr>\n";
}
The page I am posting to looks like this:
<?php
$commenter_user_id = $_SESSION['user_id'];
$body = substr($_POST['comment'],0,400);
$post_id=;
add_comment($commenter_user_id,$post_id,$body);
$_SESSION['message'] = "Your comment has been added!";
header("Location:/social_learning/site_pages/profile.php");
?>
You can use hidden input:
<input type="hidden" name="postName" value="<?= $list['id'] ?>" />
Then in your PHP it's available in $_POST['postName'] (in accordance to the name attribute of the hidden input)

Categories