Retrieve a selection of drop down list in php - php

I retrieved the selection of drop down from database. Now, I want to edit the entries. When I open the page for edit, I should have the selected data of drop down displayed in the page.
I used the following code to populate the drop down list.
<?php
try {
$sql1 = "select vehicleno from vehicle";
$projresult = $dbh->query($sql1);
$projresult->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Some problem getting data from database !!!" . $e->getMessage());
}
echo '<select name="vehicleno" id="vehicleno" class="form-control" required value="<?php echo htmlentities($result->vehicleno);?>>';
$vno=$_POST['vehicleno'];
while ( $row = $projresult->fetch() ) {
echo '<option value="'.$row['vehicleno'].'">'.$row['vehicleno'].'</option>';
}
echo '</select>';
?>

You can't set the value of a select box directly in html, therefore as you loop through the options you'd have to check if that is the option selected. For example...
echo '<select name="vehicleno" id="vehicleno" class="form-control" required';
$vno = $_POST['vehicleno'];
while ( $row = $projresult->fetch() ) {
echo '<option value="' . $row['vehicleno'] . '"' . ($vno == $row['vehicleno'] ? 'selected' : '') . '>'.$row['vehicleno'].'</option>';
}
echo '</select>';
If this was your parent page and you wanted to send the value to a subpage such as edit-vehicle.php then you'd have to use a form element...
echo '<form action="edit-vehicle.php" method="post"><select name="vehicleno" id="vehicleno" class="form-control" required';
$vno = $_POST['vehicleno'];
while ( $row = $projresult->fetch() ) {
echo '<option value="' . $row['vehicleno'] . '"' . ($vno == $row['vehicleno'] ? 'selected' : '') . '>'.$row['vehicleno'].'</option>';
}
echo '</select></form>';
See https://www.w3schools.com/php/php_forms.asp for more about php form handling.

Related

Insert to database information with select option php

I try to insert some information to database i need to select and option then to remember the last option so i don't select all the time same option
The problem with me code is it remembers the last loop.
<form action="" method="post">
<select name="db_tablelist" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
<?php
$result = mysqli_query($con,"SHOW TABLES");
while($row = mysqli_fetch_array($result)) {
if (isset($_POST['db_tablelist']) == $row[0]){
echo '<option value="' . $row[0] . '" selected="selected" >'.$row[0].'';
}
else
{
echo '<option value="' . $row[0] . '">'.$row[0].'';
echo '';
}
}
echo '</select>';
?>
Your code has problem when you are mapping post data with db data. You are checking post with isset function but you are also mapping immediately. So you have add one more condition with & operator.
This should be work.
if (isset($_POST['db_tablelist']) and $_POST['db_tablelist'] == $row[0]){
echo '<option value="' . $row[0] . '" selected="selected" >'.$row[0].'';
}
I think the problem is here:
if (isset($_POST['db_tablelist']) == $row[0])
You're checking if isset result equals to $row[0]

Print selected attribute on select option with PHP and MySQL

I'm printing a select list from my database.
Here's a part of my code:
<form action="" method="post">
<div class="form-item">
<select name="specialties">
<?php
$query = "SELECT * FROM specialties";
$result = mysqli_query($connection, $query);
echo '<option value="All">' . $filterTitle . '</option>';
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$title = $row['title_'. $lang];
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
echo '<option value="' . $id . ' "' . $selected . '>' . $title . '</option>';
}
?>
</select>
</div>
<div class="form-item">
<input class="form-submit" type="submit" name="submit" value="<?php echo $filterSubmit; ?>">
</div>
</form>
In this form when I choose some of the options, it filters the content. That's working properly and I don't need to post that part of the code.
First when I choose some option from the select list and after submit, it filter the content, but the select option shows the All value, instead of the selected option. After that I've tried with the code above and now when I submit the form, the select value shows the last option and all the options has selected attribute.
How can I change that logic, so when I select let's say the second option, after submitting the form, the selected attribute will appear only on the second option, so the text will be the second option?
CONCLUSION:
Thank you guys for your answers. You're all correct. I gave you all +1 and I choose the Hassaan's answer, because it's very well explained.
Currently you are checking/comparing values and generating variable. You need to use else condition because you must change/reset the value of generated variable. See the example below.
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
else
$selected = '';
Add an else clause to reset the selected attribute to an empty string.
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
else{
$selected = '';
}
You need to make empty selected variable every time like below
while($row = mysqli_fetch_assoc($result)) {
$selected = '';
$id = $row['id'];
$title = $row['title_'. $lang];
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
echo '<option value="' . $id . ' "' . $selected . '>' . $title . '</option>';
}

MySQL Select based on drop down value

I have the following code:
<?php
session_start();
include_once("config.php");
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
echo '<select name="dropdown" value=""><option value="">Dropdown</option>';
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
echo "</select>";
?>
the values of the drop down box are filled from the database.
I was wondering if theres a way to have a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table?
any information will help!
Thanks
Ok, resontant81, you want to fill a table depending on the option selected, next code does exactly what you want, the explanation comes just after :
<html>
<head>
<title>My list</title>
<script type="text/javascript">
//----------------------------------------------------------------
// SENDS SELECTED OPTION TO RETRIEVE DATA TO FILL TABLE.
function send_option () {
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
//----------------------------------------------------------------
</script>
</head>
<body>
Click on any option
<br/>
<select id="my_select" onchange="send_option();">
<option>Select an option</option>
<?php
//----------------------------------------------------------------
// LIST FILLED FROM DATABASE (ALLEGEDLY).
for ( $i = 0; $i < 5; $i++ )
{ $text = chr($i+65) . chr($i+65) . chr($i+65);
echo "<option value='" . $text . "'>" . $text . "</option>";
}
//----------------------------------------------------------------
?>
</select>
<br/>
<br/>
<table>
<?php
//----------------------------------------------------------------
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
for ( $i = 0; $i < 4; $i++ ) // DISPLAY ROWS.
{ echo "<tr>";
for ( $j = 0; $j < 6; $j++ ) // DISPLAY COLUMNS.
echo "<td>" . $_POST["my_option"] . "</td>"; // DISPLAY OPTION.
echo "</tr>";
}
else echo "<tr><td>Table empty</td></tr>";
//----------------------------------------------------------------
?>
</table>
<!-- FORM TO SEND THE SELECTED OPTION. -->
<form method="post" action"01.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
</body>
</html>
To make things easier for you (and for me), I am not using a database, all you have to do is copy-paste previous code to a text file, rename it "01.php" (because that's the action of the form, you can change it), and run it in your browser, is ready to use.
The dropdown is filled from database (in this case, with letters), when an option is selected the page reloads with the selected option and fills the table.
You said: "a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table". This select statement you want you must put it right after the line :
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
So your select statement will take the selected option from $_POST and use it to retrieve the right data and display it.
Let me know if it helps you.
This is the code to fill the dropdown, it's my code with yours combined:
// LIST FILLED FROM DATABASE (ALLEGEDLY).
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['Category'] . "'>" . $row['Category'] . "</option>";
Next edit is to fill the table. Change the query for the right one if it's not right :
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
$query = "SELECT Category FROM books where category like '" . $_POST["my_option"] . "'";
$result = mysqli_query ($mysqli, $query);
while( $row = mysqli_fetch_array($result) )
echo "<tr>" .
"<td>" . $row['book_name'] . "</td>" .
"<td>" . $row['author'] . "</td>" .
"<td>" . $row['Category'] . "</td>" .
"</tr>";
I'm assuming $mysqli is your db connection and it's made through config.php. I'm also assuming that category is a column name in the books table. It is up to you to sanitize and validate the user input. This is simply an example to get you started.
page.php ....
<?php
session_start();
include_once("config.php");
function categories() {
global $mysqli;
$result = "";
$stmt = "SELECT Category FROM books GROUP BY Category";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
$result .= '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
mysqli_free_result($sql);
mysqli_close($mysqli);
return $result;
}
IF (isset($_POST['ThisForm'])) {
$category = htmlspecialchars(strip_tags(trim($_post['dropdown'])));
$stmt = "SELECT * FROM books WHERE category ='$category'";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
// do something with result
}
// free result and close connection
mysqli_free_result($sql);
mysqli_close($mysqli);
}ELSE{
// base form
echo '<form action="page.php" name="something" method="post">';
echo '<select name="dropdown" value=""><option value="">Dropdown</option>'.categories().'</select>';
echo '<input type="submit" name="ThisForm" value="submit" />';
echo '<form>';
}
?>

PHP: select current option

I have a DB table with all categories (id, category) and table with all of events (id, event, categoryID).
And on the event editing form I have the select field with all of the categories (getting from the DB). But sinse I'm developing an editing form, I need to select current category by default.
This is my select field (PHP method that gets all the categories from DB and puts them in the following order):
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3">Cat3</option>
<option value="4">Cat4</option>
<option value="5">Cat5</option>
Let's say, current event is under category 3, so I need the following HTML to be generated:
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3" selected>Cat3</option>
<option value="4">Cat4</option>
<option value="5">Cat5</option>
How do I achieve it with PHP, if I have the catID?
Hopefully, this question is clear enough. Sorry for my bad explanation
UPD: This is my PHP code that generates category list:
public function getCatList($conf) {
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM categories";
$result = $mysqli->query($query);
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['id'] . '">' . $row['category'] . '</option>';
}
}
Appending to your while iteration a condition will solve this for you:
while($row = mysqli_fetch_array($result)) {
$isSelected = $row['id'] == $catID;
echo '<option '.($isSelected ? 'selected="selected"' : '').' value="' . $row['id'] . '">' . $row['category'] . '</option>';
}
You're making a comparison if the current value is the same as that stored in $catID - and store the boolean result in a variable. In the echo you're just doing a conditional forking and appending the selected attribute if the value was true, otherwise not appending any empty string.
You can do it like
while($row = mysqli_fetch_array($result)) {3
echo '<option value="' . $row['id'] . '"';
//if condition is met then make the option selected
if($row['categoryID'] == 3) {
echo " selected='selected' ";
}
echo '>' . $row['category'] . '</option>';
}
you should add the selected catID as a parameter to your getCatList-function. Then just change the creation of your HTML to include the selected-attribute:
public function getCatList($conf, $catID = 0) {
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM categories";
$result = $mysqli->query($query);
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"' . ($row['id']==$catID?' selected':'') . '>' . $row['category'] . '</option>';
}
}
now you can just pass the catID to your function:
$myConf = "something";
$myCatID = 3;
getCatList($myConf, $myCatID);
//query for the categories and options
$current_value = 3;
$total_num_of_options = mysql_num_rows($your_query_result);
for($count = 1; $count <= $total_num_of_options){
echo "<option value='".$count."' ";
if($count == $current_value)
echo "selected";
echo ">cat".$count."</option>";
}

Mark an option as selected

I am populating a dropdown menu with data in a database, using this code:
$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query);
$results = mysqli_num_rows($execute);
if ($results!=0) {
echo '<label>The galleries are: ';
echo '<select id="galleries" name="galleries">';
echo '<option value=""></option>';
for ($i=0; $i<$results; $i++) {
$row = mysqli_fetch_array($execute);
$name = htmlspecialchars($row['galleryName']);
echo '<option value="' .$name. '">' .$name. '</option>';
}
echo '</select>';
echo '</label>';
}
I want to add the selected=selected to the option selected and then use that option in another query, but I have problem adding the selected tag in the actual selected entry.
More INFO:
I am using dropzone.js to upload images, and I want to select the category on the fly. The category has to be selected from the dropdown menu and used in the INSERT query.
if you have a form with POST then the code is
$selected = "";
if($_POST['galleries']==$name) $selected=" selected='selected'";
echo '<option value="' .$name. '"'.$selected.'>' .$name. '</option>';
Just as an example try this,
$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query);
$results = mysqli_num_rows($execute);
if ($results!=0) {
echo '<label>The galleries are: ';
echo '<select id="galleries" name="galleries">';
echo '<option value=""></option>';
for ($i=0; $i<$results; $i++) {
$row = mysqli_fetch_array($execute);
$name = htmlspecialchars($row['galleryName']);
if( $i == 1 )
{
$sel = 'selected="selected"';
}
else
{
$sel = '';
}
echo '<option value="' .$name. '"'. $sel .' >' .$name. '</option>';
}
echo '</select>';
echo '</label>';
}
If you want to select a specific option then you are going to have a variable containing that specific option example:
$conditionalName = "Mark";
$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query);
$results = mysqli_num_rows($execute);
if ($results!=0) {
echo '<label>The galleries are: ';
echo '<select id="galleries" name="galleries">';
echo '<option value=""></option>';
for ($i=0; $i<$results; $i++) {
$row = mysqli_fetch_array($execute);
$name = htmlspecialchars($row['galleryName']);
echo '<option value="' .$name. '"'; if($name=$conditionalName){ echo ' selected=selected';} echo '>'. $name. '</option>';
}
echo '</select>';
echo '</label>';
}

Categories