I have code that basically uploads a spreadsheet of data, could have 5 columns or 10 columns or whatever. Each column needs to have a drop down box specifying the data type, and the data types selected should be submitted via post with a form to another php site. How would I do this, this is the code that creates the elements.Is there a way to dynamically create elements, like delimist . attCount, and how would i put this loop into an html form to submit the data? Is there any way to put the values of all of these into an array for convince? Thanks.
EDIT: Ok thanks for the dynamic stuff, but how would i put this into a form and submit this via post to another page. Or is there another way to post information. I dont know much about php.
while($attCount < count($attArray)) {
echo "<select name=\"delimList\">";
echo "<option value=1>tab</option>";
echo "<option value=2>comma</option>";
echo "<option value=3>semi-colon</option>";
echo "<option value=4>ampersand</option>";
echo "<option value=5>pipe</option>";
echo "</select>";
$attCount = $attCount + 1;
}
Using a foreach loop and assigning the first index in your array will give you what you're expecting:
$options = [1=>'tab','comma','semi-colon','amperstand','pipe','another-value'];
echo "<select name=\"delimList[]\">\r\n";
foreach($options as $val => $option){
echo "<option value=\"$val\">$option</option>\r\n";
}
echo "</select>\r\n";
output:
<select name="delimList[]">
<option value="1">tab</option>
<option value="2">comma</option>
<option value="3">semi-colon</option>
<option value="4">amperstand</option>
<option value="5">pipe</option>
<option value="6">another-value</option>
</select>
To sumbit the page you'll need to put everything inside of
<form method="post"> // you may want to add an action="..."
.... // if you want to post to another page,
</form> // instead of the same one
You'll also need a submit button too...
<input type="submit" name="submit" value="submit" />
After submit you can check the values like this:
if(isset($_POST['delimList'])){
foreach($_POST['delimList'] as $key => $value){
echo "delimList[$key] = $value";
}
}
You can put all the value of all of these into an array… by putting all the values of these into an array!
$myArray = ['tab','comma','semi-colon','amperstand','pipe','another-value'];
echo '<select name="delimList">';
for ($i = 0; $i < count($myArray); $i++) {//Loop thru all
echo '<option value="'.$i.'">'.$myArray[$i].'</option>';
}
echo "</select>";
Related
I'm roughly new in PHP and I'm trying to display the contents of a multidimensional array in a table that was inside a select option list which has been selected by the user. What I'm trying to do is that the array key of the selected option is returned into a new variable such as $keyref = key($myarray); so that I can use the key to display inside the table but i don't know how. Do I use a javascript function such as onChange=function() in the <select> list?
Here is the code:
<?php
$tshirt = array (
array("T-shirt A",15,"XS"),
array("T-shirt B",20,"S"),
array("T-shirt C",25,"M")
); //array("t-shirt type", price, "size")
$keyRef = 0; //the variable that will contain the selected array key
echo "<select id='shirtlist'>";
foreach($tshirt as $value){
echo "<option value='$value)'>$value[0]</option>";
}
echo "</select>";
echo "<p>Details of T-shirt:</p>";
echo "<table>";
echo "<tr>";
echo "<th>T-shirt Type</th>";
echo "<th>Price</th>";
echo "<th>Size</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$tshirt[$keyRef][0]."</td>";
echo "<td>".$tshirt[$keyRef][1]."</td>";
echo "<td>".$tshirt[$keyRef][2]."</td>";
echo "</tr>";
echo "</table>";
?>
The table manage to display the data of the first array but nothing happens when I selected the other options. As for trying javascript function I tried the json_encode($myarray) method but that only returned the Array as String notice.
First of all, you have to understand that PHP is only executed server-side, which means that there is no interaction between the PHP code and the action you are achieving in the browser.
The only way to return to PHP is to send a new request.
Depending on what you want to do and which workflow you want in the browser you should choose between pure PHP (each action has to be achieved with client-server request) or using javascript (directly executed in the browser).
In pure PHP, your feature can be achieved with the following code :
<?php
$tshirt = array (
array("T-shirt A",15,"XS"),
array("T-shirt B",20,"S"),
array("T-shirt C",25,"M")
); //array("t-shirt type", price, "size")
$keyRef = 0; //the variable that will contain the selected array key
if(isset($_GET["shortlist"]) && isset($tshirt[$_GET["shirtlist"]])) {
$keyRef = $_GET["shirtlist"];
}
echo "<form method='GET'>";
echo "<select name='shirtlist'>";
foreach($tshirt as $key => $value){
$selected = '';
if ($key == $keyRef) {
$selected = 'selected';
}
echo "<option value='$key' $selected>".$value[0]."</option>";
}
echo "</select>";
echo "<input type='submit' value='submit'/>";
echo "</form>";
echo "<p>Details of T-shirt:</p>";
echo "<table>";
echo "<tr>";
echo "<th>T-shirt Type</th>";
echo "<th>Price</th>";
echo "<th>Size</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$tshirt[$keyRef][0]."</td>";
echo "<td>".$tshirt[$keyRef][1]."</td>";
echo "<td>".$tshirt[$keyRef][2]."</td>";
echo "</tr>";
echo "</table>";
?>
Note that I use the global $_GET to get the information from the URL query strings. This information is transmitted to PHP when the submit button of the form is clicked, and then the value of the select is accessible in it using the name attribute of the tag (<select name="shirtlist"> means the value is accessible in $_GET["shirtlist"] when the method of the form is GET).
This code requires an action from the user to update the page with the selection.
I also added a selected attribute to the select in order to select the displayed article (When the iteration index is the same as the requested shirtlist value).
The double check if(isset($_GET["shortlist"]) && isset($tshirt[$_GET["shirtlist"]])) { is here to be sure the selected item is in the list, as the URL is accessible to anyone it's possible to change manually the value, it's more secure to change the form method to POST and then access the value using the $_POST global array instead of the $_GET one.
Html Code:
<?php
$tshirt = array (
array("T-shirt A",15,"XS"),
array("T-shirt B",20,"S"),
array("T-shirt C",25,"M")
); //array("t-shirt type", price, "size")
?>
<!-- here we create a select box -->
<select class="" id="shirtlist">
<option value="" selected>select</option>
<!-- add the key varible into foreach loop that give the index of the value -->
<?php foreach($tshirt as $key => $value){ ?>
<option value="<?=$key?>"><?=$value[0]?></option>";
<?php } ?>
</select>
<p>Details of T-shirt:</p>
<table>
<tr>
<th>T-shirt Type</th>
<th>Price</th>
<th>Size</th>
</tr>
<tr>
<!-- Here we are created the empty table Data will be field after user select any option -->
<td class="type"></td>
<td class="price"></td>
<td class="size"></td>
</tr>
</table>
Add Jquery CDN :
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Javascript/Jquery Code :
<script type="text/javascript">
/* we we convert the PHP array into Javascript array using JSON.parse function */
var data = JSON.parse('<?=json_encode($tshirt)?>');
/* This is the code when user change the option in select box then it will add/replace the data into table */
$('#shirtlist').change(function(e){
var key = $(this).val();
$('.type').text(data[key][0]);
$('.price').text(data[key][1]);
$('.size').text(data[key][2]);
});
this will do the work.
on select box change event, it will add/replace the data into table.
I have this easy select in PHP as echo (using Chosen JS):
echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\"
data-placeholder=\"Country...\" multiple class=\"chosen-select\">
<option value=\"dontcare\">dontcare</option>";
foreach ($states as $state) {
echo "<option value=\"" . $state->stat .
"\" >" . $state->stat . "</option>";
}
echo "</select> </th></tr>";
after submitting from and refreshing page values are not as selected.
If i have select with only one choice this is working for me:
var my_val = '<?=$_POST['price']?>';
$("#cenan").val(my_val).trigger("chosen:updated");
but i dont know how to set it as selected in case of array. Can you help me and show me some code? I spent hours and hours without any result.
You are POSTing the form data to the same page and then refreshing it, right?
If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array.
Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. Much easier on the eye.
foreach ($states as $state) {
if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
echo "<option value='$state->stat' selected>$state->stat</option>";
} else {
echo "<option value='$state->stat'>$state->stat</option>";
}
}
Lets suppose you have HTML select like following :
<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
Here is the solution :
<?php
$arr = ['a','b']; // PHP Sample Array
?>
var js_json = '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']
// initialize
$("#firstselect").chosen();
// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});
//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");
I need to store all the items selected from a dropdown box inside array. I have only one form now with the select dropdown list. So each time I select an item from the list and submit the form it overwrites the previous item.
How do I make it work like each time it submits the id will be stored so that I can display all the items selected?
//this is the select dropdown for addon item
<select name="addon">
<?php
mysql_select_db($database_bumi_conn, $bumi_conn);
$query="SELECT * FROM tbl_addons WHERE status=1";
$result=mysql_query($query)or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$a_id=$row['addOns_id'];
$a=$row['addOns'];
?>
<option value="<?php echo $a_id?>"><?php echo $a;?></option>
<?php
}
?>
</select>
//And this is how I store the id
$addon_id=$_POST['addon'];
//edited with session
$_SESSION['option']=array();
$_SESSION['option'][$addon_id]=array('qty'=>$qty,'date_1'=>$date_1,'date_2'=>$date_2);
print_r($_SESSION['option']);
foreach($_SESSION['option'] as $option=>$value)
{
echo $option.'=>';
foreach($value as $val)
{
echo $val;
}
}
You could use SESSION' variables to store all the ID :
session_start();
// Rest of your code here
// $addon_id=$_POST['addon']; Becomes :
if (!in_array($_POST['addon'], $_SESSION['addons']))
$_SESSION['addons'][] = $_POST['addon'];
Edit: Not sure about your edit with sessions. You're resetting $_SESSION['option'] everytime, losing previous addon_id values
Ignoring the fact that you're using a deprecated, inherently un-secure and unmaintained extension, you need to use the multiple attribute on your <select> element and let PHP know that it will be receiving an array of values by using the [] suffix on the element name. To summarise...
<select name="addon[]" multiple>
<?php foreach($collection as $val => $label) : ?>
<option value="<?= htmlspecialchars($val) ?>"><?= htmlspecialchars($label) ?></option>
<?php endforeach ?>
</select>
The PHP variable $_POST['addon'] will then contain an array of selected values (when the form is posted of course).
This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];
here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));