Unknown output in php - php

i am trying to create a checkbox form from values in an array in php to be submitted via POST. This is the code:
<?php
$check = array('beiber' => 'dumb', 'john' => 'singer', 'michael' => 'legend', 'lovato' => 'firestarter');
$t = 1;
$name = $t;
foreach($check as $x =>$y){
$name = $t++;
echo $name;
echo ' <input type = "checkbox" name =' . $name . 'value =' . $x . '/>' . $x . $sp . $y . '<br>';
}
?>
<input name = "submit" type = "submit" value = "submit" /><br>
<?php
if(isset($_POST['submit'])){
print_r( $_POST);
}
?>
The output I get after clicking submit if all boxes are checked is:
Array ( [1value] => on [2value] => on [3value] => on [4value] => on [submit] => submit )
My question is why are they having the value 'on' and how do i fix it. Thanks.

You're outputting wrong html, change output line to:
echo '<input type="checkbox" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($x) . '" />' . htmlspecialchars($x . $sp . $y) . '<br>';
Note:
quotes around attribute values
spaces between attribute names
htmlspecialchars to escape special symbols

Related

How to add value into array php file When html form submit in php?

I have one html form as index.php and also another mydata.php file. I want to put data into mydata.php file, but there is some issue
index.php
<form action="" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<?php
if (isset($_POST['field1']) && isset($_POST['field2'])) {
if (!filesize('mydata.php')) {
$data0 = '<?php $a = array(' . "\n";
$ret = file_put_contents('mydata.php', $data0, FILE_APPEND | LOCK_EX);
}
$data = '"' . $_POST['field1'] . '"' . '=>' . '"' . $_POST['field2'] . '",' . "\n";
$ret = file_put_contents('mydata.php', $data, FILE_APPEND | LOCK_EX);
if ($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
}
?>
mydata.php
$array = array("a"=>"b");
When I add submit new value i want to need push new array like my post data
Array
(
[field1] => c
[field2] => d
[submit] => Save Data
)
$array = array("a"=>"b","c"=>"d");
You just need to add data to $array, generate the PHP code and then save it into file.
Example with PHP file:
<?php
// data for the form ($_POST), all data from the client (browser) MUST be validated and sanitized
$formData = [
'field1' => 'c',
'field2' => 'd'
];
// load mydata.php if it was not loaded before
require_once 'mydata.php';
// add new data or update existen
$array = array_merge($array, $formData);
$tab = ' ';
// generate the new content for the mydata.php file
$newContent = '<?php' . PHP_EOL . '$array = [' . PHP_EOL;
foreach ($array as $key => $value)
$newContent .= $tab . "'$key' => '" . addslashes($value) . "'," . PHP_EOL;
$newContent .= '];' . PHP_EOL;
//save the new content into file
file_put_contents('mydata.php', $newContent);
But I really recommend to you use the JSON file for that.
Example with JSON file:
<?php
// data for the form ($_POST), all data from the client (browser) MUST be validated and sanitized
$formData = [
'field2' => 'c',
'field3' => 'd'
];
$array = [];
// load data
if (file_exists('mydata.json'))
$array = json_decode(file_get_contents('mydata.json'), true);
// add new data or update the existen
$array = array_merge($array, $formData);
// save the new data into file
file_put_contents('mydata.json', json_encode($array), LOCK_EX);
I'm not sure what you are asking because the question is not clear, but if I am getting it right, to add add a new key-value pair to your existing array, you could try
$field1 = $_POST['field1']; // $field1 = "c"
$field2 = $_POST['field2']; // $field2 = "d"
$array[$field1] = $field2;

How to use php array's key array

I want to make an array of various inputs. For example that my key is submit button, and I want that my array key would be a content of what my submit button needs, also my button is connected to text field.
My minimal code:
<?php
function element($submit){
if ($submit == "submit"){
$element = "<input type = $submit value = $submit /><INPUT type = $submit name = $submit value = $submit size=40 />";
}
$content = $element ;
return $content;
} // function element
function main($submit){
//print_r ($defaults);
foreach ($submit as $k=>$submit){
#$content .=element ($submit[$k]) . "<br />\n";
}
return "<form action = {$_SERVER['PHP_SELF']} method = POST>\n$content</form>";
}
$arr = array(
"submit" => array("submit", "OK","text", "question", ""),
);
$content .= main ($arr["submit"]);
print $content;
So the problem is I don't know how to put my key array values into HTML. Maybe I am doing it wrong? And is it bad practice to do like this?
This is outputting the inputs I believe like you want. There are comments in the code for what I changed and some thoughts.
<?php
//Change param to $name of the index and $data that you will usefor readability
function element($name, $data){
//Checking that we are on the right element
$element = "";
if ($name == "submit"){
//It is confusing that you have 2 inputs here.
//Rather than hard coding 0, 1, 2, 3, 4 there could be a name
//in an associative array. This is not very flexible
//This is string interpolation I like it more hen concatenation for
//Simple put this variable here
$element = "<input type='{$data[0]}' value='{$data[1]}' /><input type='{$data[2]}' name='{$data[3]}' value='{$data[4]}' size=40 />";
}
//No need to do $content = $element then just return
//Not sure what should happen if the name does not exist...
//Right now it is an empty string
return $element;
}
function main($inputs){
//print_r ($defaults);
//Create this before just using it removes a warning.
$content = '';
//Change to $v just for clarity not sure what it will do to actual $submit.
//Loops the whole array not just that instances of submit.
foreach ($inputs as $k=>$v){
$content .= element ($k, $v) . "<br />\n";
}
return "<form action = {$_SERVER['PHP_SELF']} method = POST>\n$content</form>";
}
//Changed to inputs assuming this would be more then one
$inputs = array(
"submit" => array("submit", "OK","text", "question", ""),
);
//Lets call this form you are overusing the content and it is hard to follow
$form = main($inputs);
print $form;
You can embed variable values into a string by using the . (dot) operator in PHP (this is generally called "string concatenation"). For your code I would do it like this:
$element = "<input type='" . $btnname . "' value='" . $btnvalue . "'/><input type='" . $fieldtype . "' name=" . $fieldname . " value='" . $fieldvalue . "' size='40' />";
Or using an array (which must be defined first):
$element = "<input type='" . $sub[0] . "' value='" . $sub[1] . "' /><input type='" . $sub[2] . "' name=" . $sub[3] . " value='" . $sub[4] . "' size='40' />";
If you have an (multi-dimensional) array (with keys which are also arrays), say
$arr = array("subkey" => array($firstVar, $secondVar, [...]));
then you have to use the string concatenation like this:
$element = "<input type='" . $arr["subkey"][0] . "' value='" . $arr["subkey"][1] . "' /><input type='" . $arr["subkey"][2] . "' name=" . $arr["subkey"][3] . " value='" . $arr["subkey"][4] . "' size='40' />";
This will also work for more array subkeys (more dimensions).
You could also use string indices in your array, like the ones of $_SERVER, $_GET or $_POST by replacing the integer index by a string.
But you do not have to have a submit button connected to a text field, it can exist alone.

PHP: How to use two dimensional array to display menu?

I think I'm picking this up pretty well, but I'm just stuck on this. I want to display this menu using an array and foreach loop:
<img src="/img/page-icons/credit-card21.png" />Payments
<a target="_blank" href="/cloud"><img src="/img/page-icons/upload123.png" />Cloud</a>
<a target="_blank" href="/portal"><img src="/img/page-icons/earth208.png" />Portal</a>
So to do that I need to turn that into this line in PHP:
echo '<img src="/img/page-icons/' . $image . '" />' . $title . '';
To fill that out in the loop we need to create something like this... which is where I'm stuck:
foreach( $stamp as $link => $target ){
echo '<a href="/' . $link . '" target="' . $target . '">';
foreach( $stamp[] as $title => $image ){
echo '<img src="/img/page-icons/' . $image . '" />' . $title;
}
echo '</a>';
}
I don't really know how to go about the above, just been messing around with it for a while today. I also don't want to always display target="' . $target . '" on every link.
The array would probably be a two dimensional array? Something like this any way:
$stamp = array(
'link' => array('title' => 'image'),
'link' => array('title' => 'image'),
'link' => array('title' => 'image')
);
EDIT:
There's some confusion of what 'target' is, I want to echo 4 values from an array into a link, target is one of the values. I didn't know how to use that in the array so I just left it out.
When you do:
foreach( $stamp as $link => $target )
The $link variable contains the string "link" and the $target variable is an array such as ['title' => 'image'].
What you should probably do is have an array like this:
// Init links
$links = array();
// Add links
$links[] = array(
'title' => 'My Title',
'href' => 'http://www.google.com',
'target' => '_blank',
'image' => 'image.png',
);
foreach ($links as $link)
{
echo '<a href="'.$link['href'].'" target="'.$link['target'].'">';
echo '<img src="/img/page-icons/' . $link['image'] . '" />';
echo $link['title'];
echo '</a>';
}
This is a bit more flexible approach that lets you add other data items to the structure in the future. That $links array could easily be generated in a loop if you have a different data source such as a database as well.
EDIT
To answer your further question, you can prefix the link building with a set of sane defaults like this:
foreach ($links as $link)
{
// Use the ternary operator to specify a default if empty
$href = empty($link['href']) ? '#' : $link['href'];
$target = empty($link['target']) ? '_self' : $link['target'];
$image = empty($link['image']) ? 'no-icon.png' : $link['image'];
$title = empty($link['title']) ? 'Untitled' : $link['title'];
// Write link
echo "<a href='$href' target='$target'>";
echo "<img src='/img/page-icons/$image' />";
echo $title;
echo "</a>";
}
you can set your array like:
$stamp = array(
'0' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target),
'1' => array('title'=>$title, 'image'=>$image,'link'=>$link,,'target'=>$target),
'2' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target)
);
and in foreach you can write
$i=0;
foreach( $stamp as $st=> $target ){
echo '<a href="/' . $st['link'] . '" target="' . $st['target'] . '">';
echo '<img src="/img/page-icons/' . $st['image'] . '" />' . $st['title'];
echo '</a>';
}

How to create a SELECT element with an array of options using PHP? [duplicate]

This question already has answers here:
creating variable name by concatenating strings in php
(4 answers)
Closed 8 years ago.
Simple question, with im sure a simple answer, I just cant get it working!!
I have a function which will be passed one of 5 id's (for example "first", "second", ",third", "fourth" and "fifth").
Inside this function I want to refer to an array whose name is the id followed by _array (for example "first_array", "second_array" etc...)
How do I concatenate the id name passed to the function with the string "_array" ? I know how to do this in a string but not when referring to another variable!
To sum up i will have:
$i_d = "first" //passed to my function
$string = "_array"
and I want to link to an array called:
$first_array
EDIT
My code is the following:
$option_timescale = array ( "1"=>"Immediately",
"2"=>"1 Month",
"3"=>"2 Months",
"4"=>"3 Months",
"5"=>"4 Months",
"6"=>"5 Months",
"7"=>"6 Months",
"8"=>"No Timescale"
);
$option_bus_route = array ( "1"=>"1 minute walk",
"2"=>"5 minute walk",
"3"=>"10 minute walk",
"4"=>"No Bus Needed"
);
$option_train_stat = array( "1"=>"5 minute walk",
"2"=>"10 minute walk",
"3"=>"5 minute drive",
"4"=>"10 minute drive",
"5"=>"No Train Needed"
);
function select_box($k,$v){ //$k is the id and $v is the description for the select boxes label
$string = "option_"; //these two lines
$option_array =$string . $k; //are the troublemakers!
$buffer = '<select name="' . $k . '" id="' . $k . '">';
foreach ($option_array as $num=>$desc){
$buffer .= '<option value="' . $num . '">' . $desc . '</option>';
}//end foreach
$buffer .= '</select>';
$buffer .= '<label for="' . $k . '">' . $v . '</label>';
return $buffer;
}//end function
And the code which calls this function is:
function create_table($titles, $id) { //$titles is the relevant array from lists.php, $id is the id of the containing div
$select = array('timescale','bus_route','train_stat'); //'select' id list
$textarea = array('notes'); // 'textarea' id list
$buffer = '<div id="' . $id . '">';
foreach ($titles as $k=>$v) { //$k is the database/id/name $v is the description text
if (in_array($k,$select)){
$buffer .= select_box($k,$v);
}
else if (in_array($k,$textarea)){
$buffer .= text_box($k,$v);
}
else{
$buffer .= check_box($k,$v);
}
}
$buffer .= '</div>';
echo $buffer;
}
Add $ to eval the string.
$i_d = "first";
$string = "_array";
$myvar = $i_d . $string;
$$myvar = array('one','two','three');
print_r( $$myvar);

PHP: How to add variables and quotes to a variable

How can I add variables and quotes to a variable?
in the output it just prints the variables
This is the code I have tried
$pl2 = '{"comment":"' . $nmp3 . '","file":"' . $pmp3 . '"},';
Try with:
$pl2 = json_encode(array(
'comment' => $nmp3,
'file' => $pmp3
));
Try this, it should work:
$p = ' {"comment": ' . $nmp3;
$p = $p.' "," file " : " ' . $pmp3;
$p=$p.' "}," ';
echo $p;

Categories