I'm having a contact form field named, addons with select options
it's code is
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_name; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
Every addon have it's unique price. It can be fetch through $options->addon_price; I added only addon name in contact form so i'm getting only it's name once user submits form. Likewise, I need to get that addon price too without creating new field and asking users to select price in dropdown.
Any ideas to do this ?
You can use the following trick:
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_name.','.$options->addon_price; ?>">
<h5><?php echo $options->addon_name; ?></h5>
</option>
<?php } ?>
Add the price with the name in value of dropdown and then after submitting the page you can get the string with name and price and then you can split it with the , by using the explode function like it:
$pieces = explode(",", $str);
And you can use the price and name by $name = $pieces[0] and $price = $pieces[1].
You Can use
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_price; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
and u can fetch the price form the drop down
you can try this you will be able to get the price and it will show addon_name to the user.
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_price; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
It sounds like you need a unique ID to identify the addons. If it's a static array that doesn't change, you can even use the array keys for that purpose, but I would add an addon_id field to the objects.
The addons array would be something like this:
$addons = array(
1 => $addon1,
2 => $addon2,
3 => $addon3,
... etc
);
Your select options can have the array keys as values:
<?php foreach ($addons as $key => $options) { ?>
<option value="<?php echo $key; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
Then when you're processing the selected addon, use the key to access the appropriate addon, like so:
$selected_addon = $addons[$_POST['addon']];
, obviously substituting the correct form element name, and sanitizing the input first, this is just to give you an idea.
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 am a beginner and I have written a piece of code to use an array values inside a select form, but I don't know how to get the chosen value.
What I have :
$list = '<select><option>' .implode('</option><option>',$apn).'</option></select>';
Now I would like to get the name of the chosen value but I don't know how.I tried to add
<select name="test">
to my select form and get it with
echo $_POST['test']
but it does not work.
Thank you !
<?php $myArray = array(1 => 'red', 2 => 'blue'); ?>
<select name="theName">
<?php
foreach ($myArray as $key => $value) { ?>
<option value="<?php $key ?>"><?php echo $value ?></option>
<?php } ?>
</select>
Basically, you are looping through the option value with a foreach statement and assigning the key as the value.
You then get the chosen value with name 'theName'... echo $_POST['theName'];
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).
Let's say I have a photo upload system where the user have to set a category for each album to get the basics for a nice and clean search functionality. But if an user is changing now a value like this:
<select>
<option value="">Choose a Category</option>
<option value="Holiday">Holiday</option>
</select>
to this:
<select>
<option value="">Choose a Category</option>
<option value="Holiday">Something Stupid</option>
</select>
is "something stupid" entered into the database.
That's why I have to do a server side check. But I don't know how to get all the correct values of the option fields to compare it with the posted value.
So my first considerations were the following:
PHP:
// Get all values of the option fields
// Push all the values into an array
if (in_array('foo', $array)) {
// foo is in the array
}
Thank you for helping.
Ok, so I think I guessed what you tried to tell.
You should not have the tags hardcoded in your list.php file, but instead have an array there. That way, you can use it both for generating the select field, but also for the verification. However, generally a database table with the categories would be preferable.
path/list.php
return array(
'1' => 'Name of Ctg 1',
'2' => 'Name of Ctg 2'
);
Here you generate the select
<select name="whatever">
<?php
$options = include('path/list.php');
foreach($options as $id => $name) {
echo '<option value="' . $id . '">' . $name . '</option>';
}
?>
</select>
And how to verify it then in the "target" page
$options = include('path/list.php');
if(!array_key_exists( $valueFromUser, $options ) ) {
// invalid option
}
When the data is posted from the page containing the select tag, it will be in the $_REQUEST array, if you run this php in catcher php page:
foreach ($_REQUEST AS $key => $value) echo "$key = $value <br>";
you will see the results from your list.php.
I am trying something in my examination script. So I'd like to ask a question about my problem.
I have combobox in the exam form. like this :
<option value="<?PHP echo $answer_list['answer_value']; ?>"><?PHP echo $answer_list['answer_detail']; ?></option>
I must put another value in this. it will be like this I think:
<option value="<?PHP echo $answer_list['answer_value']; ?>,<?PHP echo $answer_list['answer_id']; ?>"><?PHP echo $answer_list['answer_detail']; ?></option>
I must save these values to the database, but I really don't know how can I save these values to the database when I exploded these values to the different columns in one table.
I tried something with explode function but I couldn't do it well.
So when I posted these values from form, I tried this function but I couldn't save them to the database.
$answers = $_POST['answers'];
$answer_explode = explode(",",$answers);
$answer_id = $answer_explode[0];
$answer_value = $answer_explode[1];
this gets only first and second value in the array. But I must make 2 variables like this :
before comma
$answer_id = values before comma
$answer_value = values after comma
how can I do that?
Name your <option> in HTML with the array syntax <option name="answers[]"> and you can access them in PHP POST as an array.