How to pass two variables from form select using POST method? - php

Supplier:* <br/><select name="supplier">
<?php foreach ($db->query($sql) as $row) { ?>
<option value="<?php echo $row['supplier_id']; ?>">
<?php echo $row['supplier_name']; ?>
</option>
<?php } ?>
</select>
Retrieving data on the next php script:
$supplier_name = ??????
$supplier_id = ?????
The above code is allowing a user to make a selection of a supplier from a supplier table.
How can I pass both the supplier_name and the associated supplier_id to two different variable from the form using POST?

Bellow you have a quick example. It's not the case to use hidden input elements.
Your select:
<select name="supplier">
<?php foreach ($db->query($sql) as $row) { ?>
<option value="<?php echo $row['supplier_id'] .'|' . $row['supplier_name']; ?>">
<?php echo $row['supplier_name']; ?>
</option>
<?php } ?>
</select>
Php script that processes the form:
if(isset($_POST['supplier']) {
$arr = explode('|', $_POST[supplier]);
if( count($arr) == 2 ) {
$supplierId = $arr[0];
$supplierName = $arr[1];
}
}

The easiest way would be to do something like:
<option value="<?php echo $row['supplier_id'].';'.$row['supplier_name']; ?>">
<?php echo $row['supplier_name']; ?>
</option>
And then evaluate them like so:
$values = explode( ';', $_POST['supplier_info'] );
$supplier_id = $values[0];
$supplier_name = $values[1];
But it would be better to only transmit the id and then llokup the name of the supplier when evaluating the $_POST-Data

Related

How to display values already selected in a select (PHP)

In need some help on this.
I have a form with a select who works perfectly and add all the values selected in my database. But now I want to do my update form, and I want that when I click to modify a user and arrive on the form, the values are already selected.
For example if in my first form, if I had selected the values 1 and 2, I would like 1 and 2 to be already selected when i go to the modification form. I've already did that :
<?php
$nomLogiciel = getDemandeNomLogiciel($id_demande)[0];
$nom = explode(", ", $nomLogiciel);
foreach ($nom as $item) {
$profilsTmp = getProfilByLogiciel($item); ?>
<div class="form-floating mb-3">
<select class="form-control selectpicker" id="id_profil" name="id_profil[]" multiple data-live-search="true">
<?php foreach ($profilsTmp as $item2) { ?>
<option value="<?php echo $item2['id_profil']; ?>"><?php echo $item2['profil']; ?></option>
<?php } ?>
</select>
<label for="id_profil">Profil <?php echo $item ?></label>
</div>
<?php } ?>
I already managed to do it with a simple select like this :
<select class="form-control selectpicker" id="nomPole" name="nomPole">
<option value="Ambulatoire" <?php if ($one['pole'] == "Ambulatoire") { echo ' selected="selected"'; } ?>>Ambulatoire</option>
<option value="Habitat et Vie Sociale" <?php if ($one['pole'] == "Habitat et Vie Sociale") { echo ' selected="selected"'; } ?>>Habitat et Vie Sociale</option>
</select>
But I would like to know how to do it with multiple values in a foreach ?
If you need my SQL function :
function getDemandeNomLogiciel($id_demande) {
global $bd;
$stmt = $bd->prepare('SELECT nom_logiciel FROM demandes WHERE id_demande = :id_demande');
$stmt->bindParam(ID_DEMANDE, $id_demande);
$stmt->execute();
return $stmt->fetch();
}
function getProfilByLogiciel($nomLogiciel) {
global $bd;
$stmt = $bd->prepare('SELECT * FROM profils_logiciels WHERE nom_logiciel = :nomLogiciel');
$stmt->bindParam(NOM_LOGICIEL, $nomLogiciel);
$stmt->execute();
return $stmt->fetchAll();
}
Thanks for your help !
I tried this and it worked very well. I just check if the values of my previous request can be found in the database. If yes I select them :
<?php
foreach ($structures as $item) { ?>
<option value="<?php echo $item['id_structure']; ?>"
<?php if ($item['id_structure'] == $structurePrincipaleID['id_structure']) { echo ' selected="selected"'; } ?>>
<?php echo $item['nom_structure'] ?></option>
<?php } ?>

Option selected with codeigniter and data from DB

I use codeigniter to create a dropdownlist with customers.
If I enter selected, than the last customer in the dropdown is automatically choosen.
Is it possible to select a customer inside that foreach?
My code snippet:
<?php foreach ($customers as $c): ?>
<option value="<?php echo $c->customer_id;?>"><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>
Yes it is. However you have to know which customer is chosen at the moment, and then inside the loop check if the chosen customer_id is the same as the current one:
<?php
$chosenCustomer_id = 5; //of course don't hardcode it
foreach ($customers as $c):
$selected = $c->customer_id == $chosenCustomer_id ? 'selected' : '';
?>
<option value="<?php echo $c->customer_id;?>" <?php echo $selected; ?>> <?php echo ><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>
Just add ternary condition in <option> inside for loop where $selectedOption is your value to be selected.
<?php $selectedOption = "yourvalue";
foreach ($customers as $c): ?>
<option value="<?php echo $c->customer_id;?>" <?= ($c->customer_id == $selectedOption ? "selected" : "")><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>
Use selected attribute in Option Tag
Selected needs to be set based on condition
$selected=(condition): "selected","";
<option <?php echo $selected; ?>> Option Inner Html </option>
Compare variable with attribute in option tag
<?php $chosenCustomer_id = 5;?>
<select name="customer" required>
<?php foreach ($customers as $c){?>
<option <?=($chosenCustomer_id==$c['customer_id']?'selected="selected"':'')?> value="<?=$c['customer_id']?>"><?=$c['customer_name']?></option>
<?php }
?>
</select>

How to use SELECTED with array filled select form

Here is my code.
$result = mysqli_query($link, 'SELECT product_name FROM products');
while ($row = mysqli_fetch_array($result))
{
$products[] = array('product_name' => $row['product_name']);
}
<select name="products" id="products">
<option name="search_product" value="All Products"<?php if (isset($search_product_selected) AND $sort_product_selected == "All Products") { echo ' SELECTED'; } ?>> All Products</option>
<?php foreach ($products as $product): ?>
<option name="search_product" value="<?php echo $product['product_name'];"><?php echo $product['product_name']; ?></option>
<?php endforeach; ?>
</select>
This is part of a form that reloads the same page, adjusting the items shown on the page. The form works perfectly, and the search works perfectly, but how do I use SELECTED to highlight which product was selected in the previous search?
Compare the value with your search word, if they are equal then put selected into the option.
<?php foreach ($products as $product): ?>
<option name="search_product" value="<?php echo $product['product_name'];?>"<?php echo $product['product_name'] === $_POST['search_key'] : ' selected' : '' ?>><?php echo $product['product_name']; ?></option>
<?php endforeach; ?>

how do i set a value of a multiple <select> tag from the database

i am selecting an entry from the database to be edited on php/html. i can call the values of a table from the database and put it in a multiple tag.
$job_exp_tags = $row[16];//value from another table
$job_tags = explode(',',$job_exp_tags);//array to be put "selected" on the multiple select tag
$sql_2 = "SELECT _id, job_name from job_tags";
$sel_2 = mysql_query($sql_2);
$array = array();
while($row_new = mysql_fetch_assoc($sel_2)){
$array[] = $row_new;
}
<tr>
<td>Job Experience:<br>
(Hold ctrl to select multiple)</td>
<td><select name = 'job_tags[]' multiple>
<?php
foreach($array as $value){ ?>
<option value ='<?php echo $value['_id']; ?>'> <?php echo $value['job_name']; ?> </option>
<?php
}
?>
</select> </td>
</tr>
my problem is how can i put selected values to it from the explode statement
edit:
i've solved the problem, thanks anyway guys!
<option value ="<?php echo $value['_id']; ?>" <?php echo in_array($value['_id'], $job_tags) ? 'selected="true"' : null; ?>><?php echo $value['job_name']; ?></option>
Just check if its in your array, if so, set it selected:
foreach($array as $value){ ?>
$selected = in_array($value, $job_tags) ? ' selected ' : '';
/* Or [selected="selected"] if you dont use html5 yet (which you should) */
<option value ='<?php echo $value['_id']; ?>' <?php echo $selected; ?>> <?php echo $value['job_name']; ?> </option>
<?php
}
Your code can be simplified though:
foreach($array as $value){
$selected = in_array($value, $job_tags) ? ' selected="selected" ' : '';
?>
<option value="<?=$value['_id']?>" <?=$selected?> > <?=$value['job_name']?> </option>
<?php
}
I changed the quotes arround the value to doubles, not really a rule, but it is a good practice to do so. The other change is the short echo. Small demo, both do the same:
<php $var = 'foorbar'; ?> <!-- A bit weird, but this is demo-purpose -->
<span><?php echo $var; ?></span>
<span><?=$var?></span>
You could look for the value in the string $job_exp_tags and if found set the selected property.
foreach($array as $value){
$selected = strpos($job_exp_tags, $value) ? 'selected' : '';
echo '<option value="'.$value['_id'].'" '.$selected.'>'.$value['job_name'].'</option>';
}

Foreach php function inside HTML select options

Im a newbie to this forum and have just started coding in php. Need some help. I have the following code
<?php error_reporting(-1);
require_once('/mysql/sql_connect.php');
$q = "SELECT pty.pty_profile_name AS profile FROM pty, users WHERE users.username = 'testaccount' ";
$r = #mysqli_query ($dbc, $q);
$results_array = array();
while($row = mysqli_fetch_assoc($r)) {
array_push($results_array, $row);
echo "<pre>"; print_r($results_array); echo "</pre>"; }
?>
<p>
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
<input type="submit" name="Submit" />
</form>
<?php
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
The output I get is correct, but it displays the key, eg, 0 or 1 or 2, based on what I select in the form. I need the value output. Eg 0 = Emerton, it outputs "0" instead of Emerton.
If I echo $value['profile'] instead of pty_select, I get the last result of the query all the time. Which in this example would be 2, which is Ambarvale as I believe it just chooses the last row output of the query.
I hope I've made sense. Thanks in advance.
It will obviously echo the key, as you assigned the value of options as $key
if you need the options in the $_POST['pty_select'] use this:
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $value['profile'];?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
You mean you need the value what you have used to display it.
Then,
Change to :
<option value="<?php echo $value['profile']; ?>">
<?php echo $value['profile']; ?>
</option>
And now let's go to ideal world :)
Build data pairs database_id => name for options:
$q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users
WHERE users.username = 'testaccount'";
$r = mysqli_query($dbc, $q);
$values = array();
while($r = mysqli_fetch_row($r)) {
$values[$r[0]] = $r[1];
}
Never use # when working with database, why do you want to suppress errors instead of preventing/handling them?
Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:
function selectbox( $values = array(), $attributes = array(), $selected_value = null)
{
// Header
echo '<select';
foreach( $attributes as $key => $val){
echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
}
echo '>';
// Values
foreach( $values as $key => $val){
echo '<option value="' . htmlspecialchars( $key) .'"';
if( $key === $selected_value){
echo ' selected="selected"';
}
echo '>' . htmlspecialchars( $val) . '</option>';
}
echo '</select>';
}
And now usage :)
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<?php selectbox( $values, array( 'name' => 'pty_select')); ?>
<input type="submit" name="Submit" />
</form>
And what to do with it then?
$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
$name = $values[$id];
}
Give
<option value="<?php echo $value['profile']; ?>"><?php echo $value['profile']; ?></option>
instead of
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
Change it to something like
if(isset($_POST['Submit'])) {
echo $results_array[$_POST['pty_select']]['profile'];
}
Or alternatively use profile option value.

Categories