Creating dynamic dropdown lists - php

I want to create dynamic select lists. For example: I have 5 students in my db. My goal is to create 5 selects ,and in every select all students which are in database. So if user inserts a 6th student in the database, the page should display 6 selects, and in every select names of 6 students.
I've tried with this code, but it only creates 1 select, containing 4 students(the first one from the db is missing).
The Code:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
while($result=mysqli_fetch_array($execute))
{
echo '<select name=student'.$i.'>';
echo '<option value="-1" >Choose student</option> <br/>';
while($res=mysqli_fetch_array($execute))
{
echo '<option value='.$res["id_student"].'>'.$res["name"].'</option> <br/>';
}
echo '</select>';
$i++;
}

$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++) {
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute)) {
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
$i++;
}
$select .= '</select>';
}
echo $select;
UPDATE
inside the while
$select = '<select name=student' . $j . '>';
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] .
change this lines by this other
$select = '<select name="student' . $j . '">';
$select .= '<option value="' . $res["id_student"]."'>' . $res["name"] .
we missed the double quotes for value and in select name

Problem solved, I just needed to insert vars $exe and $execute inside for loop, so after every iteration $result is refreshed,otherwise it just prints options in first select...
CODE:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++)
{
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute))
{
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
}
$select .= '</select>';
}
echo $select;

Related

Create months as options for select tag using php

I need to create a select tag with months as options using php
like this:
<option value='01'>JAN</option>
<option value='02'>FEB</option>
... and so on
here is my try - without success
<select>
<?php
$str = '{"01":"JAN","02":"FEB","03":"MAR","04":"APR","05":"MAY","06":"JUN","07":"JUL","08":"AUG","09":"SEP","10":"OCT","11":"NOV","12":"DEC"}';
$obj = new stdClass(json_decode($str));
foreach($obj->$key as $key=>$val){
echo "<option value = '" . $key . "'>" . $val . "</option>";}
?>
</select>
<?php
for($month = 1; $month <= 12; $month++) {
echo '<option value="' . $month . '">' . strtoupper(DateTime::createFromFormat('!m', $month)->format('M')) . '</option>';
}
Dont make life so complicated
<?php
$arr= ['01'=>'JAN', '02'=>'FEB', '03'=>'MAR', '04'=>'APR',
'05'=>'MAY', '06'=>'JUN', '07'=>'JUL', '08'=>'AUG',
'09'=>'SEP', '10'=>'OCT', '11'=>'NOV', '12'=>'DEC'
];
foreach($arr as $key=>$val){
echo "<option value = '" . $key . "'>" . $val . "</option>";
}
?>

PHP Bootstrap multi select options

In my code I am using PHP which populates the bootstrap multi selectpicker from MySQL database but the problem is it only selects the last option instead of multiple options, I don't know what I am missing in it? Here is my my code
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $tablenames;
$result = mysqli_query($conn, $sql);
if( ! $result ) {
echo mysql_error();
exit;
}
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';
$array = explode(',', $selectedopt);
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
echo '</select>';
}
To get all selected values in a multiselect you need to use name attribute with []:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
After that you can iterate over $_POST[$comboname] with a foreach.
Update:
Let's look closer to your code here:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
Rewrite it as:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}

How to retain the value of Select Option inside a For Loop using PHP

I have a working code below. Basically, the code prints the options 50 times and 4 is the default selected option.
for ($i = 1; $i <= 50; $i++) {
if($i == 4){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
but every time i click the submit button, the option field resets back to the selected option even though the variables was captured properly.
It would be good if the option selected by the user is preserved after the button was clicked and the only time it reset back to the selected defaults is if the page was refreshed.
check if the value is sent by post if not assign 4 to the variable option
<form action="#" method="post" accept-charset="utf-8">
<select name="select">
<?php
if(isset($_POST['select']))
{
$option= $_POST['select'];
}
else
$option=4;
for ($i = 1; $i <= 50; $i++) {
if($i == $option){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
?>
</select>
<input type="submit" name="" value="Sumbit">
</form>
This should do it - it uses the value sent from the client if it exists, or 4 if not.
if (isset($_POST['selected_value'])) {
$selected = $_POST['selected_value'];
} else {
$selected = 4;
}
for ($i = 1; $i <= 50; $i++) {
if($i == $selected){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
Take value from posted field, say "select", if exist then take it as selected otherwise your default value.
Using below code:
$selected = (isset($_POST['select']) ? $_POST['select'] : 4);
for ($i = 1; $i <= 50; $i++) {
if($i == $selected){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}

Check if any comma seperated value exists inside loop values

I get some values from an old db of a client as such:
$query = "SELECT rowid,source FROM `".$table."`";
$result = mysql_query($query);$temp=0;$p = array();
while ($row = mysql_fetch_array($result)) {$p[$temp] = $row;$temp++;}
and then I loop through the values as such:
// loop through all possible values
foreach ($p as $obj) {
}
Inside the foreach loop I will print <option> element and I want to determine the <option selected/> elements. The selected elements could be more than 1, since its a multiselect form.
First thing I check whether a $selected value equals to rowid.
// check if exists equals to rowid
if ($obj["rowid"] == $selected){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
This works just find if $selected = "1" (or any single digit)
My problem and my question comes if $selected = "3,4". Then I need to loop through the values and separate the comma-separated values inside foreach ?
Here is my complete code:
$selected = "3,4";
$query = "SELECT rowid,source FROM `" . $table . "`";
$result = mysql_query($query);
$temp = 0;
$p = array();
while ($row = mysql_fetch_array($result)) {
$p[$temp] = $row;
$temp++;
}
// loop through all possible values
foreach($p as $obj) {
// check if exists equals to rowid
if ($obj["rowid"] == $selected) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
else {
// check if default exists with comma separated values
if (!empty($default) && strpos($selected, ',') !== false) {
$arr_values = explode(',', $selected);
// loop through comma-separated values to get the selected items
foreach($arr_values as $selected) {
if ($obj["rowid"] == $default) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
}
// $return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
else {
$return.= '<option value="' . $obj["rowid"] . '">' . $obj["source"] . '</option>';
}
}
}
Just use in_array() + explode() functions combination to check if rowid exists in selected string
if (in_array ($obj["rowid"], explode(",",$selected))){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
Explanation: E.G. if $selected = "3,4" then explode(",",$selected) return you array(3,4) and in_array check if $obj["rowid"]' exists in that array so it mean you will have in you output multiple <options with attribute selected set

How do i define from which table that specific column comes from?

I made a page in which one can edit the prices for each article that each webshop has. The price that it already has is in the textfield and it can be changed to whatever the user may want. Then the user hits the Edit (Wijzigen is Dutch for Edit) button and it should change to whatever was in the textfield before pressing it.
But I'm having quite some trouble with the UPDATE query since I need to give it some ID's to select the right one. And, as you'll be able to see in the source, right after starting the while() loop, I can't specify the right ID from the right table.
I would appreciate it if you could help me out with what I need to change, add or delete to make this work.
<?php
include 'inc/inc.php';
$artikel = mysqli_query($mysql, "SELECT a.Artikel_ID, a.Productnaam, aw.Artikel_ID, aw.Webshop_ID, aw.Prijs, w.Webshop_ID, w.Shopnaam FROM artikel a, artikel_webshop aw, webshops w WHERE a.Artikel_ID = aw.Artikel_ID AND aw.Webshop_ID = w.Webshop_ID GROUP BY aw.Webshop_ID, aw.Artikel_ID");
echo '<table id="specialtable"><tr style="background-color:#F8F8F8;"><td>Productnaam</td><td>Webshop</td><td>Prijs</td><td>Wijzigen</td></tr>';
$i = 0;
$j = 1;
while($artikelR = mysqli_fetch_assoc($artikel)) {
$artikel_id = $artikelR['Artikel_ID'];
$webshop_id = $artikelR['Webshop_ID'];
echo '<form method="post">';
if($i == 0){
echo '<tr style="background-color:#DDD;">';
$i = $i + 1;
}else{
echo '<tr style="background-color:#F8F8F8;">';
$i = $i - 1;
}
echo '<td>' . $artikelR['Productnaam']. '</td><td>' . $artikelR['Shopnaam'] . '</td><td>€ <input type="text" name="' . $j . '" value="' . $artikelR['Prijs']. '"></td>';
echo '<td><input type="submit" name="' . $j . '" value="Wijzigen"></td></tr></form>';
$jNew = $_POST['' . $j . ''];
$j++;
$test = $_POST['' . $j . ''];
if(isset($test)) {
$sql = mysqli_query($mysql, "
UPDATE artikel_webshop
SET Prijs = '" . $jNew . "'
WHERE Artikel_ID = '$artikel_id'
AND Webshop_ID = '$webshop_id'");
echo 'U heeft succesvol de prijs van het artikel ' . $artikelR['Productnaam'] . ' van de webshop ' . $artikelR['Shopnaam'] . ' gewijzigd.<br><br>';
$url = 'prijsWij.php';
echo '<meta http-equiv="refresh" content="4;URL=' . $url . '">';
}
}
echo '</table></form>';
?>
Edit
I finally got it to work. I'm pretty bad at explaining, so I'll just add the new code:
<?php
include 'inc/inc.php';
$artikel = mysqli_query($mysql, "
SELECT a.Artikel_ID, a.Productnaam, aw.Artikel_ID as awa_id, aw.Webshop_ID as aww_id, aw.Prijs, w.Webshop_ID, w.Shopnaam
FROM artikel a, artikel_webshop aw, webshops w
WHERE a.Artikel_ID = aw.Artikel_ID
AND aw.Webshop_ID = w.Webshop_ID");
echo '<table id="specialtable"><tr style="background-color:#F8F8F8;"><td>Productnaam</td><td>Webshop</td><td>Prijs</td><td>Wijzigen</td></tr>';
$i = 0;
$j = 1;
while($artikelR = mysqli_fetch_assoc($artikel)){
$artikel_id = $artikelR['awa_id'];
$webshop_id = $artikelR['aww_id'];
echo '<form method="post">';
if($i == 0){
echo '<tr style="background-color:#DDD;">';
$i = $i + 1;
}else{
echo '<tr style="background-color:#F8F8F8;">';
$i = $i - 1;
}
echo '<td>' . $artikelR['Productnaam']. '</td><td>' . $artikelR['Shopnaam'] . '</td>';
echo '<td>€ <input type="text" name="prijsTest" value="' . $artikelR['Prijs']. '"></td>';
echo '<td><input type="submit" name="' . $j . '" value="Wijzigen"></td></tr></form>';
$kNew = $_POST['prijsTest'];
$test = $_POST['' . $j . ''];
$j = $j + 1;
if(isset($test)){
$sql = mysqli_query($mysql, "
UPDATE artikel_webshop
SET Prijs = " . $kNew . "
WHERE Artikel_ID = '$artikel_id'
AND Webshop_ID = '$webshop_id'");
echo 'U heeft succesvol de prijs van het artikel ' . $artikelR['Productnaam'] . ' van de webshop ' . $artikelR['Shopnaam'] . ' gewijzigd.<br><br>';
$url = 'prijsWij.php';
echo '<meta http-equiv="refresh" content="4;URL=' . $url . '">';
}
}
echo '</table></form>';
?>
SELECT a.Artikel_ID as a_id, a.Productnaam, aw.Artikel_ID as aw_id ...
In order to know which article was updated, you need to keep track of it in your form so that when the form gets submitted, you will be able to update the correct article.
It seems like you have one form per article. In this case, it's easy. When you generate your form, add a hidden input containing the article ID:
<input type="hidden" name="article_id" value="<?php echo $articleId; ?>"/>
When the form will be submitted, the article ID will be posted along with the new price. You can retrieve it through $_POST['article_id']. Then, you can use this variable in your MySQL query to update the right article!

Categories