Foreach php function inside HTML select options - php

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.

Related

How to retain dropdown selected option after submit / page refresh

I want to have dropdown selected option selected after submit/refresh page. I search for other examples but no one works on my code.
How to retain selected value after submit/refresh with this code?
<form name="test" action="test.php?id=<?php echo $row["id"]; ?>" method="post">
<select id="test_email" name="test_email">
<option value="">...select</option>
<?php
$sql2 = "SELECT test_id, test_email FROM test WHERE status='Act'";
$res = $db->query($sql2);
if ($res->num_rows > 0) {
while($row1 = mysqli_fetch_array($res)) {
?>
<option value="<?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?>"><?php echo $row1['test_id'];?></option>
<?php
}
}
?>
</select>
Solved this way:
Because I could not pass $_POST['test_email'] with <?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?>
Because I use explode on $_POST['test_email']
I make one more post (insert in db) $test_temp = trim(mysqli_real_escape_string($db, $_POST['test_email'])); to have my dropdown value (whole string) in db.
I added hidden input in my form <input id="test_temp" type="hidden" name="test_temp" value="<?php echo $row["test_temp"]; ?>">
And changed select option line to <option value="<?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>"<?php if($row1['test_email'] . '-' . $row1['test_id'] == $row['test_temp']) echo ' selected="selected"' ; ?>><?php echo $row1['test_id'];?></option>.
Perhaps this could be simpler but it works like a charm.
#roberto06: Thank you for your guidance.
You need to add the selected="selected" attribute on the option matching your $_POST value.
You might also want to concatenate <?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?> into <?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>, but that's up to you.
Here's a solution (I assumed that $POST['test_email'] has to be equal to $row1['test_email'] . '-' . $row1['test_id'] in order for the condition to be matched). I'm using a shorthand if...else here, but you could also use a classic if :
<form name="test" action="test.php?id=<?php echo $row["id"]; ?>" method="post">
<select id="test_email" name="test_email">
<option value="">...select</option>
<?php
$sql2 = "SELECT test_id, test_email FROM test WHERE status='Act'";
$res = $db->query($sql2);
if ($res->num_rows > 0) {
while($row1 = mysqli_fetch_array($res)) {
?>
<option value="<?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>"<?php echo (isset($_POST['test_email']) && $row1['test_email'] . '-' . $row1['test_id'] == $_POST['test_email']) ? ' selected="selected"' : ''; ?>><?php echo $row1['test_id'];?></option>
<?php
}
}
?>
</select>
</form>

How to fill <select> with options using PHP and SQL?

My question is: I want to show all SQL answers from a specific table inside the <select> using php.
I have tried to get it working, but without much success as it only shows one result.
<?php
error_reporting(E_ALL);
include 'connect.php';
include 'header.php';
set_time_limit(10);
$cat = $bdd->query('SELECT cat_id,cat_name,cat_description FROM categories');
$categories_list = $cat->fetch();
While ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
}
$cat->closeCursor();
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
?>
That's totally not the way to do it. Have a separation between PHP and HTML. And make sure you have the option echoed out inside the loop. Something like this:
<form method="post" action="accès/create_topic_post.php">
<label for="sujet">Sujet :
<input type="text" name="sujet" id="sujet" required autofocus>
</label>
<label for="cat">Catégories :
<select name="topic_name">
<?php
// Loop it here.
while ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
?>
</select>
</label><!-- You forgot this -->
<input type="submit" value="Envoyer" />
</form>
There are two approach to achieve your desired output.
Approach One:
Store cat_name in a new array and use it in your HTML or anywhere, where you want to use.
<?php
$cat_name = array();
while($categories_list = $cat->fetch()) {
$cat_name[] = $categories_list['cat_name'];
}
?>
<select name="topic_name">
<?php
foreach ($cat_name as $key => $value) {
?>
<option value="<?=$value?>" ><?=$value?> </option>
}
?>
</select>
Approach 2:
<?php
while ($categories_list = $cat->fetch()) {
?>
<option value="<?=$categories_list['cat_name']?>" ><?=$categories_list['cat_name']?> </option>
<?php
}
?>
Whats wrong with your code:
$cat_name = $categories_list['cat_name']; this will only store the last value of your query, you must need to store the value in an array or use <option> inside the while() loop.
You keep replacing cat_name every time you read data from the SQL server. You need to store it in an array
<?php
error_reporting(E_ALL);
include 'connect.php';
include 'header.php';
set_time_limit(10);
$cat = $bdd->query('SELECT cat_id,cat_name,cat_description FROM categories');
//$categories_list = $cat->fetch(); This line discards a row of data
$cat_names = array(); //array for category names
While ($categories_list = $cat->fetch()) {
//Add newest 'cat_name' to the array
$cat_names[] = $categories_list['cat_name'];
}
$cat->closeCursor();
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
//Loop and read back each category name
foreach ($cat_names as $cat_name){
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
?>
You don't have to loop over results manually, as PDO has a function that can do it for you already, called fetchAll(). You have to use it instead of fetch() if you want to get an array of rows.
However, beside it, you need to learn PHP and programming in general. Because your current code makes little sense. To output an array, you have to use a loop:
$cat = $bdd->query('SELECT cat_name FROM categories');
$categories_list = $cat->fetchAll(PDO::FETCH_COLUMN); // here it is
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
foreach ($categories_list as $cat_name)
{
echo "<option value='$cat_name'>$cat_name</option>";
}
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
Move the fetch loop to the output section of your code.
So instead of this:
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
move the loop so it will look like this:
While ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
Use while loop while you're outputting the category in select option.
Like this,
While ($categories_list = $cat->fetch()) {
echo "<option value=\"".$categories_list['cat_name']."\" >$categories_list['cat_name'] </option>";
}

code for fetching value to select option

I have select option. this option has multiple value from database. I want to update something from database, this value i want to update is exist on the select option I have.
this is my option code
$id = $_GET['update'];
$query = mysql_query("SELECT * FROM transaction where id = '$id'") or die ("could not search");
$count = mysql_num_rows($query);
while ($rows = mysql_fetch_array($query)) {
$id = $rows['id'];
$tranid = $rows['tranid'];
$trandate = $rows['trandate'];
$patientid = $rows['patientid'];
$transactiontype = $rows['transactiontype'];
$trandescription = $rows['trandescription'];
$tranquantity = $rows['tranquantity'];
$tranunitprice = $rows['tranunitprice'];
$tranamount =$rows['tranamount'];
$gettrandescription = $rows['trandescription'];
}
}
if (isset($_POST['selectmedicine'])) {
$gettrandescription=$_POST['medicineid'];
}
if (isset($_POST['selectroomquantity'])) {
$tranquantity=$_POST['quantity'];
}
?>
<script type="text/javascript">
$('#collapseone').collapseone({
toggle: true
});
<option value="<?php echo $trandescription; ?>" <?php if($trandescription==$gettrandescription){ echo "selected";} ?> ><?php echo $gettrandescription; ?></option>
<option value="<?php echo $tranquantity; ?>" <?php if($tranquantity==$tranquantity){ echo "selected";} ?> ><?php echo $tranquantity; ?></option>
this has value results, but i cant fetch this value to my existing select option.
If you want to "make that variable an array" as aldrin27 said, append [] to the name attribute of the select tag. The selected value of the option with name selectroomquantity will be available in your script as $_POST["selectroomquantity"] (this is the varible).
<select multiple name="selectroomquantity[]">
<option value="...">...</option>
</select>
It should only be necessary if multiple options can be selected however.
Also, there seems to be a typo:
<?php if($tranquantity==$tranquantity)
That check will always return true. It should probably be:
<?php if($tranquantity==$gettranquantity)
hi all i just got the code on how to fecth the value to dropdown. actually i made a wrong word. pre-selected is the right one, sorry for that. here;s the working code.
<select name="selectmedicine" class="form-control col-sm-4" id="medicinename">
<option id="0" style="width:100px"></option>
<?php
$medicine = mysql_query("SELECT * FROM medicine");
while ($row = mysql_fetch_array($medicine)) {
echo '<option id="' . $row['medicinename'] . '"';
echo ' value="' . $row['medicineid'] . '"';
if($row['medicinename'] == $trandescription) {
echo ' selected="selected"';
}
echo '>';
echo $row['medicinename'];
echo '</option>';
}
?>
</select>
thanks everyone, whos trying to help me on this. actually this is my five revised question sorry for that. and finally i got the right one.

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

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

Multiple Select with Explode: only returns the word "Array"

Using Wordpress I have created a multiple select box so that users can select categories to exclude. When the page initially loads I see my default values pre-selected. However when I select new values and save... I only see the word "Array" echoed and nothing selected?
<select class="amultiple" id="<?php echo $value['id']; ?>" name="<?php echo $value['id']; ?>[]" multiple="multiple" size="8">
<?php
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] );
}
}
$categories = &get_categories('type=post&orderby=name&hide_empty=1');
if ($categories) {
$ex_cat = implode(',', $tt_cat_exclude);
foreach ($categories as $category) {
$selected = (in_array($ex_cat, $category->cat_ID)) ? ' selected="selected"' : '';
echo '<option value="' . $category->cat_ID . '"' . $selected . '>' . $category->cat_name . '</option>' . "\n";
}
}
?>
</select>
<br />For testing purposes, print variables: <?php echo $ex_cat; ?>
http://i48.tinypic.com/k9e3qq.gif
You should use implode()
Like so
$ex_cat = implode(',', $tt_cat_exclude);
This will return a comma separated list
This line should be
$selected = (in_array($category->cat_ID, $ex_cat)) ? ' selected="selected"' : '';
Changed to
$selected = (in_array($category->cat_ID, $tt_cat_exclude)) ? ' selected="selected"' : '';
Since the $ex_cat is a string and cannot be used in in_array()
The $ex_cat is now redundant i guess.
Looks like tt_cat_exclude is missing it's opening $
name="tt_cat_exclude[]" means you're defining an array, so it's normal for the output to be "array"
for testing try print_r (outputs the whole architecture of the variable)
or var_dump (outputs the var type too)
When you postback, the field tt_cat_exclude is an array of the values that you've set - because you've name it tt_cat_exclude[] with a [] behind.
Example:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select class="amultiple" id="tt_cat_exclude" name="tt_cat_exclude[]" multiple="multiple" size="8">
<option value="1">TestingA</option>
<option value="2">TestingB</option>
<option value="3">TestingC</option>
<option value="4">TestingD</option>
<option value="5">TestingE</option>
</select>
<input type="submit" value="Submit" />
</form>
<br/><br/>For testing purposes: <?php
if(isset($_POST['tt_cat_exclude'])){
var_dump($_POST['tt_cat_exclude']); // outputs an array of the selected values
}
?>

Categories