Posting an array into a php document - php

I want to be able to post an array containing...
$food = array (
'food_1' => 'ice cream ',
'food_2' => 'pizza'
);
<input type="text" id="in_foods[]" value="<?=$food;?>" />
to another page but it does not seem to be working. what am I doing wrong?

A cleaner solution will be to:
1- convert the array into a string using the implode function:
$foods = implode(',',$foods);
2- Place it in the input text field to be submitted:
<input type="text" id="foods" value="<?=$food;?>" />
3- On the other page convert the string back to an array:
$foods = explode(',',$_POST['foods'])
Try ;)

You can't just post a data structure like that. You should be getting a notice saying you're trying to convert an array to string.
Consider putting your array into a session instead. That way it stays as an array between calls.
session_start();
$_SESSION['food'] = $food;

Try with this code :
<?php
$food = array (
'food_1' => 'ice cream ',
'food_2' => 'pizza'
);
$food = implode(",", $food);
?>
<input type="text" id="in_foods[]" value="<?=$food;?>" />

As $food is an array.
<input type="text" id="in_foods[]" value="<?
if (isset($food)) { echo $food['food_1'].', '.$food['food_2']; } ?>"
/>
If size of $food array is not defined then you can use implode function to make it as single string and can echo it.

I guess you wan't to tick foods you like out of a predefined list of foods or something like this. In this case an <input type="text"> field is not the right choice. Use <input type="checkbox"> instead (or a <select multiple>).
$foodOptions = array('burger', 'vergtables', 'berries')
foreach($foodOptions as $foodOpt) {
$checked = in_array($foodOpt, $foods)?' checked':null;
echo '<input type="checkbox" value="' , $foodOpt , '" name="in_foods[]"', $checked ,'><br>';
}

Related

Show only the specific indexed array

How can I show only the specific index? For example, here's my UI.
As you can see in the picture I have 3 checkboxes and 3 textboxes with array value.
Let's say these are the name of the element.
<input type="checkbox" name="check[]">
<input type="text" name="textbox[]">
Then print the array:
$check = $_POST['check'];
$total_rec = $_POST['textbox'];
echo 'Check Array<br>';
print_r($check);
echo '<br<br><br><br>';
echo 'TextBox Array<br>';
print_r($textbox);
Result:
Check Array
Array ( [0] => 2 )
TextBox Array
Array ( [0] => [1] => 2 [2] => )
As you can see in textbox array all index showed, all I want is to show only the specific index with value and that is the 1 => 2 only.
use empty(), return true if contain value, example :
//iterate each $total_rec's member
foreach($total_rec as each){
//if $each not empty, do something
if(!empty($each)){
echo $each;
}
}
You are using $total_rec for post values of both checkbox and text. You can filter the array of text input like this:
$total_rec_text = $_POST['textbox'];
$total_rec_text = array_filter($total_rec_text, function($arr){
return !empty($arr) ? true : false;
});
You need to loop over $_POST array and check if checkbox is checked.
If checked, then only, get/print value.
Also, in HTML, you need to add specific counters to both checboxes and
textboxes.
As only checked checboxes get posted and texboxes get posted by
default.
<input type="checkbox" name="check[0]">
<input type="text" name="textbox[0]">
<input type="checkbox" name="check[1]">
<input type="text" name="textbox[1]">
<input type="checkbox" name="check[2]">
<input type="text" name="textbox[2]">
if (isset($_POST['check'])) {
foreach ($_POST['check'] as $idx => $value) {
echo "<br/>" . $_POST['check'][$idx] . ' ' . $_POST['textbox'][$idx];
}
}

Echoing part of a PHP string back within conditional value of HTML form field

I am building an HTML form - a simplified, two field version of which is below. The user is meant to enter something like the below string into the first field of the form:
https://www.facebook.com/dialog/feed?app_id=12345&link=http%3A%2F
%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&
description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&
caption=Something
I am trying to split this string so that only the following part of the string is echoed into the second field of the form:
horse-picture.jpg
If the first field is empty, the second field is echoing back its own value. I've marked where the trouble is below. I've seen several threads on using explode, but the part of the string I'm looking to echo back isn't flanked with the same consistent characters, and the length of this string will vary, so preg_match also seems to be not a good option. Having this nested within a conditional is also throwing me off. Would very much appreciate help. Thanks!
<h2>THIS IS AN HTML FORM</h2>
<form action="sharefile.php" method="post">
<label for="decode">FB decode:<br /></label>
<input type="text" id="decoder" name="decoder" size="70" value="" /><br /><br />
<label for="img">Image (e.g. horse-picture.jpg):<br /></label>
<input type="text" id="img" name="img" size="70" value="
<?php if (strlen($_POST['decoder']) > 0)
//THIS IS WHERE THE TROUBLE STARTS
{SOMETHING GOES HERE}
//THIS IS WHERE THE TROUBLE ENDS
else {echo $_POST['img'];}
?>"
<input type="submit" value="Submit!" name="submit" />
</form>
Something like this might work. I believe you want to parse the picture URL, yes?
<?php
function scrub($string) {
// Parse the picture variable.
$matches = array();
$result = preg_match("/picture=([^\&]+)/", $string, $matches);
$url = $matches[1];
// Scrub the picture URL.
$result = preg_replace('/https?:\/\/[^\/]+\//', '', $url);
print_r($matches);
print_r($result);
}
scrub("https://www.facebook.com/dialog/feed?app_id=12345&link=http%3A%2F%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&caption=Something");
/*
Result:
Array
(
[0] => picture=https://website.com/horse-picture.jpg
[1] => https://website.com/horse-picture.jpg
)
horse-picture.jpg
*/
It looks like you're trying to parse URLs. PHP has functions for that, of course, albeit slightly weird functions, but it's PHP, so we expect that:
$url = '.. your massive URL inception ..';
$_url = parse_url($url);
print_r($_url);
parse_str($_url['query'], $query);
print_r($query);
$_url = parse_url($query['picture']);
print_r($_url);
$picture = basename($_url['path']);
var_dump($picture);
Example: http://3v4l.org/GKKmq#v430
Another method. Since this is a URL, first split on the question mark ? and take the second element, the query string. Now split on the ampersands & and loop through them looking for the key/value pair starting with "picture=". Once that is found grab the portion of the element after that many characters (8 characters in "picture="), then split the string on the forward slash / and grab the last element in that resulting array.
If $_POST['decoder'] equals:
https://www.facebook.com/dialog/feedapp_id=12345&link=http%3A%2F%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&caption=Something
Then:
list($d, $q) = explode('?', $_POST['decoder']);
$pairs = explode('&', $q);
foreach ( $pairs as $value ) {
if ( !(strpos($value, 'picture=') === FALSE) ) {
$picture = explode('/', substr($value, 8));
$picture = $picture[count($picture) - 1];
break;
}
}
echo $picture;
Outputs:
horse-picture.jpg
You should do something like this:
<?php echo '<input type="text" id="img" name="img" size="70" value="'.$whatyouwant.'"'; ?>
Hope it helps!

pass associative array in input field in form PHP

I want to know the best and easiest way to pass associative array in form inside input field. So far Ive done this and it all started to look messy and hard to handle.
$dish_result = $obj->getAll_dish();// this returns array all the rows in dish table
<form action='order_process.php' method='post'>
foreach ($dish_result as $dish){
echo '<input id="" name="dish_name[]" type="checkbox" value="'. $dish['dish_name'].'">';
echo '<input id="" name="dish_number[]" type="checkbox" value="'. $dish['dish_number'].'">';
}
</form>
Now on the order_process.php I have
foreach($_POST['dish_name'] as $dish){
echo $dish;
}
foreach($_POST['dish_number'] as $num){
echo $num;
}
What I wanted is an associative array, but how can I associate it the form dynamically. in other words I wanted to achieve this on the order_process.php.
$dishes = array(
//'dish_name' => dish_number
'chickencurry' => '70',
'onionbhajis' => '22'
// and so on.
);
Thank you very much in advance.
Create a grouping name first, then to get that kind of structure, make the dish name as key, then the value attribute holds the number. The basic idea is this:
name="dish[dishname]" value="dish_number"
It'll be like this:
echo '<input id="" name="dish['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'" />';
When you submit it with all the checkbox checked, it should be something like:
Array
(
[chickencurry] => 1
[onionbhajis] => 2
)
On the order_process.php page, just call it just like you normally do:
$dishes = $_POST['dish'];
foreach($dishes as $dish_name => $dish_number) {
}
Sample Output
You can add an index to array postdata. Try this:
foreach ($dish_result as $dish){
echo '<input id="" name="dishes['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'">';
}
Your data will then be an associative array of the checked elements when posted back.

Get all variables sent with POST?

I need to insert all variables sent with post, they were checkboxes each representing a user.
If I use GET I get something like this:
?19=on&25=on&30=on
I need to insert the variables in the database.
How do I get all variables sent with POST? As an array or values separated with comas or something?
The variable $_POST is automatically populated.
Try var_dump($_POST); to see the contents.
You can access individual values like this: echo $_POST["name"];
This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”
If your post data is in another format (e.g. JSON or XML, you can do something like this:
$post = file_get_contents('php://input');
and $post will contain the raw data.
Assuming you're using the standard $_POST variable, you can test if a checkbox is checked like this:
if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
...
}
If you have an array of checkboxes (e.g.
<form action="myscript.php" method="post">
<input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
<input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
<input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
<input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
<input type="checkbox" name="myCheckbox[]" value="E" />val5
<input type="submit" name="Submit" value="Submit" />
</form>
Using [ ] in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox'] won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.
For instance, if I checked all the boxes, $_POST['myCheckbox'] would be an array consisting of: {A, B, C, D, E}. Here's an example of how to retrieve the array of values and display them:
$myboxes = $_POST['myCheckbox'];
if(empty($myboxes))
{
echo("You didn't select any boxes.");
}
else
{
$i = count($myboxes);
echo("You selected $i box(es): <br>");
for($j = 0; $j < $i; $j++)
{
echo $myboxes[$j] . "<br>";
}
}
you should be able to access them from $_POST variable:
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val<br />\n";
}
It is deprecated and not wished to access superglobals directly (since php 5.5 i think?)
Every modern IDE will tell you:
Do not Access Superglobals directly. Use some filter functions (e.g. filter_input)
For our solution, to get all request parameter, we have to use the method filter_input_array
To get all params from a input method use this:
$myGetArgs = filter_input_array(INPUT_GET);
$myPostArgs = filter_input_array(INPUT_POST);
$myServerArgs = filter_input_array(INPUT_SERVER);
$myCookieArgs = filter_input_array(INPUT_COOKIE);
...
Now you can use it in var_dump or your foreach-Loops
What not works is to access the $_REQUEST Superglobal with this method. It Allways returns NULL and that is correct.
If you need to get all Input params, comming over different methods, just merge them like in the following method:
function askForPostAndGetParams(){
return array_merge (
filter_input_array(INPUT_POST),
filter_input_array(INPUT_GET)
);
}
Edit: extended Version of this method (works also when one of the request methods are not set):
function askForRequestedArguments(){
$getArray = ($tmp = filter_input_array(INPUT_GET)) ? $tmp : Array();
$postArray = ($tmp = filter_input_array(INPUT_POST)) ? $tmp : Array();
$allRequests = array_merge($getArray, $postArray);
return $allRequests;
}
So, something like the $_POST array?
You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.
Why not this, it's easy:
extract($_POST);
Using this u can get all post variable
print_r($_POST)

Is there some list of input's IDs or names of Form after the script was sent?

Let's imagine I got this:
index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php
<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
Script.php:
Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.
Is there a way to do this?
i may be missing something in your question, but the $_POST variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
print "Name: {$name} Value: {$value} <br />";
}
Use an array_keys on the $_POST variable in script.php to pull out the names you created and use those to get the values.
$keys = array_keys( $_POST );
foreach( $keys as $key ) {
echo "Name=" . $key . " Value=" . $_POST[$key];
}
It sounds like you're using a class or framework to generate your forms, you need to read the documentation for the framework to see if/where it's collecting this data.

Categories