PHP: select current option - php

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>";
}

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>';
}

Show all tables from database into select form in php

Hiho,
I have a little problem with showing all table names on page in form .
Code bellow:
<select name="users" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysql_list_tables($db_name);
for ($i = 0; $i < count(mysql_num_rows($result)); $i++){
echo '<option value="' . mysql_tablename($result, $i) . '">' . mysql_tablename($result, $i) . '</option>';
}
echo '</select>
</form>
<br>
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';
I try with mysqli too ,and i get results but still without names of the tables and nothing can be select.
Maybe someone know how to get this work.
First, you definitely want to be using MySQLi, as the MySQL extension is deprecated. Second, you can probably get all of the data you need in a simple SELECT query like this:
select `TABLE_NAME` from information_schema.tables
Try this
$mydbname = 'database_name';
$con=mysqli_connect("localhost","my_user","my_password",$mydbname);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$options = '';
// for the query you can use two of the following lines (line1+line2 OR line3+line4)
//Use line (line1+line2)
$result = mysqli_query($con,"SHOW TABLES");
$column_name ='Tables_in_'.$mydbname;
// OR (line3+line4
$result = mysqli_query($con,"SELECT TABLE_NAME AS tbl FROM information_schema.tables" WHERE TABLE_SCHEMA = \"'.$mydbname.'\"; ");
$column_name ='tbl';
while($row = mysql_fetch_array($result))
$options .= '<option value="' . $row[$column_name] . '">' . $row[$column_name] . '</option>';
echo '<select name="users" onchange="showTables(this.value)">';
echo '<option value="0">Select a table:</option>';
echo $options;
echo '</select>';
I modify code to this:
<select name="db_tablelist" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysqli_query($con,"SHOW TABLES");
while($row = mysqli_fetch_array($result)) { echo '<option value="' . $row[0] . '">'.$row[0].''; } echo '';
echo '</select>
</form>
<br>
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';
And now everything works .

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>';
}

Using <select> on an update form

I have an edit form with two fields: name and category. The category field is stored in the database as a number. I would like to associate each number (3 in total) to a string in the edit form and display the category recorded in the database and then the other.
<form>
<input type="text" name="name" value="<?php echo $result->name; ?>">
<select name="categoria">
<option value="<?php echo $result->category; ?>">books</option>
<option value="2">cds</option>
<option value="3">dvds</option>
</select>
</form>
I'm not sure if there was a question there, but I think I know what you're trying to do. I don't know what your table structure is like, so this is just an example.
$sql = mysqli_query("SELECT * FROM categories ORDER BY category_title ASC");
while($row = mysqli_fetch_array($sql))
{
$num = $row['category_number'];
$val = $row['category_title'];
echo '<option value="' . $num . '">' . $val . '</option>';
}
That will give you all of the options for your select element, set their value to the number from the database, and display the name of the category for the viewer.
EDIT:
Here's using the MySQLi class, which will save you some time. However, there's not much use in building a class for this particular function. It's so short.
$mysqli = new MySQLi($host, $user, $pass, $database);
$sql = $mysqli->query("SELECT * FROM products ORDER BY category_name ASC");
while($row = $sql->fetch_array())
{
$num = $row['category'];
$val = $row['category_title'];
echo '<option value="' . $num . '">' . $val . '</option>';
}
EDIT 2:
Just use the while() loop, rather than do...while(). It'd go like this:
$dbh = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$sth = $dbh->query("SELECT * FROM products ORDER BY category_name ASC");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$num = $row['category'];
$val = $row['categoty_name'];
echo '<option value="' . $num . '">' . $val . '</option>';
}

Categories