Build Combobox with Item Selected - php

Trying to create a combo box with the user's current value selected. I'm thinking my issue is with the apostrophe's and quotes - can anyone with a sharp eye help? Variable $MCI is created before any quotes/apostrophes and is functioning properly.
$MCI = '';
$MCI = $row['MobileCarrierID'];
echo '
<select name="MobileCarrierName">
<?php
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");
echo "<option value=" . $row['MobileCarrierID'] . $MCISelected . ">" . $row['MobileCarrierName'] . "</option>";
}
?>
</select>';
Thank you!

You have
echo '
<select name="MobileCarrierName">
<?php
$sql=
which needs to be changed to
echo '<select name="MobileCarrierName">';
$sql=
Also
$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");
needs to be changed to
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
And your mysqli_query is missing the database connection ie
mysqli_query($db,$query);
Finally, close off with
echo '</select>';
Your quotes and brackets are off and you've placed your selected variable inside your value in the option, a complete edited code should look something like...
<?php
echo '<select name="MobileCarrierName">';
$sql = mysqli_query($conn, "SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
echo '<option '.$MCIselected.' value="'.$row["MobileCarrierID"].'">'.$row["MobileCarrierName"].'</option>';
}
echo'</select>';
Check out How to set an option from multiple options or array with different values to views as selected in select box using PHP for a guide on how it works

<?php
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
?>
<select name="MobileCarrierName">
<?php
while ($row = mysqli_fetch_array($sql)){
$MCI = $row['MobileCarrierID'];
$MCISelected = ($MCI==$row["MobileCarrierID"]) ? " selected" : "";
echo "<option value=".$MCI." ".$MCISelected.">".$row['MobileCarrierName']."</option>";
}
?>
</select>
try this one

Related

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 .

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

Find previously selected option in while loop

I'm trying to get a drop down menu to keep its selected value when the user hits submit, but it fails due to errors on the form.
I have a while loop returning values from a database to build the options for the drop down, but how do I echo "selected" on the right option?
I have tried if($district == $row["name"]) { echo "selected";} as you see below, but it doesn't work.
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>
Sorry for the delay. None of the suggested answers worked for me. Any other ideas?
Can you try this,
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
$district = $_REQUEST['name']; // You need pass the value you have been submitted
while ($row = mysql_fetch_array($result)) {
$selected ="";
if(trim($district) == trim($row["name"])) { $selected = "selected";}
echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>
Try this..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
I just found the answer. This is what I did:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
It seems to have been this line
echo '<option value="{$row["name"]}"';
that was causing the problem.

Printing a selected value in the drop down list using php?

I have trying to print the selected value in the drop down list, but in vain. I am new to php and html, so this might sound like a stupid question but please help me out! this is my code:
echo '<tr><td>Client:</td><td><select name="client_name">';
$sql = mysql_query("SELECT * FROM client");
$s= mysql_query("SELECT project.client_id, client_name, client.client_id FROM client,project where project.client_id=client.client_id AND project_id='$editId'");
// $s2= mysql_fetch_array($s);
while ($row = mysql_fetch_array($sql))
{
while ($s2==mysql_fetch_array($s))
{
if ($row['client_id'] == $s2['client_id'])
$selected = "selected=\"selected\"";
else
$selected = " ";
}
echo '<option value="' . $row['client_id'] . '" ' . ($selected == $row['client_id'] ? ' selected' : '') . '>' . $s2['client_name'] . '</option>';
}
This code doesnt work. Please help me out! Is there a different way to do it?
Try this
echo '<tr><td>Client:</td><td><select name="client_name">';
$sql = mysql_query("SELECT * FROM client");
$s= mysql_query("SELECT project.client_id, client_name, client.client_id FROM client,project where project.client_id=client.client_id AND project_id='$editId'");
// $s2= mysql_fetch_array($s);
while ($row = mysql_fetch_array($sql))
{
while ($s2==mysql_fetch_array($s))
{
if ($row['client_id'] == $s2['client_id'])
$selected = "selected=\"selected\"";
else
$selected = " ";
}
echo '<option value="' . $row['client_id'] . '" ' . $selected . '>' . $s2['client_name'] . '</option>';
}`
This query is a problem
$s= mysql_query("SELECT project.client_id, client_name, client.client_id FROM client,project where project.client_id=client.client_id AND project_id='$editId'");
you are trying to get two client ids project.client_id and client.client_id, in such cases you should give aliases like project.client_id as project_client_id and client.client_id as client_client_id, then use that value to compare in while loop.
Note use whichever client id you want either project_client_id or client_client_id.

Categories