need some help completing my code what it does is searches in the tables of my DB for all the sections pointing to the parent_sections=2 and then prints the results in a select tag i would like some help with the sql query to check if the parent_sections=2 has child's and if so to print them with a optgroup style anyway please check the images below they explain what i need.
PHP & SQL CODE:
<?php
include('../application_top.php');
function get_title_sections($id){
$sections_query = tep_db_query("select title_sections_detail from sections_detail where id_sections = '" . (int)$id . "' and id_lang='0' order by title_sections_detail");
$result='';
while ($sections = tep_db_fetch_array($sections_query)) {
$result=$sections['title_sections_detail'];
}
return $result;
}
?>
<form>
<select name="sections">
<option selected="selected" value="">Please choose an option</option>
<?php
$sections_sql=tep_db_query("select p.id_sections, d.title_sections_detail as title from sections p, sections_detail d where p.id_sections=d.id_sections and d.id_lang='0' and p.status_sections='1' and p.parent_sections='2' order by d.title_sections_detail asc");
while ($sections = tep_db_fetch_array($sections_sql)) {
$id_sec=$sections['id_sections'];
$title_sec=get_title_sections($id_sec);
?>
<option value="<?php echo $id_sec ?>" ><?php echo $title_sec ?></option>
<?php }?>
</select>
</form>
SQL table sections:
SQL table sections_detail:
RESULT:
RESULT I NEED:
Here is my solution:
<?php
include('../application_top.php');
function load_sections($id_parent) {
$sections_sql = tep_db_query("select p.id_sections, d.title_sections_detail as title
from sections p, sections_detail d
where p.id_sections=d.id_sections
and d.id_lang='0'
and p.status_sections='1'
and p.parent_sections='".$id_parent."'
order by d.title_sections_detail asc");
$sect = array();
while ($sections = tep_db_fetch_array($sections_sql)) {
$sections['childs'] = load_sections($sections['id_sections']);
$sect[] = $sections;
}
return($sect);
}
function print_section($sect) {
if (count($sect['childs'])) {
echo "<optgroup label=\"".htmlentities($sect['title'])."\">\n";
foreach ($sect['childs'] as $subsect) {
print_section($subsect);
}
echo "</optgroup>\n";
} else {
echo "<option value='".$sect['id_sections']."'>".htmlentities($sect['title'])."</option>\n";
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form>
<select name="sections">
<option selected="selected" value="">Please choose an option</option>
<?php foreach (load_sections(2) as $sect) print_section($sect); ?>
</select>
</form>
</body>
</html>
Be aware that nesting opgroups is not allowed; only one optgroup level is allowed, as you can also read here.
Related
First option of select must be the name referring to the ID. The remaining select options are the remaining names
<select class="input" name="client_id">
<?php
$sel_client_detail="Select * from client WHERE client_id=".$id."";
$result_detail = mysqli_query($con,$sel_client_detail);
while($new_record_row = mysqli_fetch_assoc($result_detail)) { ?>
<option selected><?php echo $row['nome'];?></option>
<?php };?>
<?php
$sel_client="Select * from client";
$result = mysqli_query($con,$sel_client);
?>
<option>-----------</option>
<?php while($new_record_row = mysqli_fetch_assoc($result)) { ?>
<option><?php echo $new_record_row['nome'];?></option>
<?php };?>
</select>
Output:
<select>
<option selected> Izzi (current ID name)</option>
<option> ____________</option>
<option> Other existing clients</option>
<option> Other existing clients</option>
<option> Other existing clients</option>
<option> Other existing clients</option>
</select>
If you want the user to be first in your option list just run the query once and build the HTML parts in 2 seperate strings. Then once the loop is complete put them together and echo them
<?php
echo '<select class="input" name="client_id">';
$itsme = '';
$others = '<option>-----------</option>';
$sql = "Select * from client";
$result = $con->query($sql);
while($row = $result->fetch_assoc()){
if ( $id == $row['id'] ) {
$itsme = "<option selected='selected'>$new_record_row[nome]</option>";
} else {
$others += "<option>$new_record_row[nome]</option>";
}
}
// put the option tags together in the order you specified
echo $itsme . $others . '</select>';
Here's a different, but more conventional, approach to this common scenario:
Why not just make the chosen ID selected when you get to it in the list? Then it will still show to the user first. It's more efficient than having two separate queries.
Like this:
<select class="input" name="client_id">
<?php
$sel_client="Select * from client";
$result = mysqli_query($con,$sel_client);
?>
<option>-----------</option>
<?php while($new_record_row = mysqli_fetch_assoc($result)) { ?>
<option <?php echo ($new_record_row["client_id"] == $id ? "selected": ""); ?> ><?php echo $new_record_row['nome'];?></option>
<?php };?>
</select>
Student looking for help.
Trying to populate a dropdown menu from a mysql database, no data being showed in dropdown. Using getCategory function to get data from tables categories. Database is connecting and the particular table is being accessed through another function. I'm lost on this one, been looking and googling for the answer for last number of nights, still no luck. Maybe I've been looking at it too long that my brains fried?
Function Code
public function getCategory()
{
echo $query = "SELECT * FROM `categories`";
$results = mysqli_query($this->_con, $query) or die(mysqli_error());
$categories = array();
foreach ($results as $result){
$categories[$result['id']] = $result['category_name'];
}
mysqli_close($this->_con);
return $categories;
echo "<pre>"; print_r($categories); echo "</pre>";
}
Dropdown Code
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<?php foreach ($categories as $key=>$category){ ?>
<option value="<?php echo $key; ?>"><?php echo $category; ?></option>
<?php } ?>
</select>
Table called categories
Columns are id & category_name
please try the below code in your code in your function
$nums=mysql_num_rows($results);
for($i=0;$i<$nums;$i++)
{
$id=mysql_result($results,$i,'id');
$category=mysql_result($results,$i,'category_name');
$categories[$id] = $category;
}
$categories =getCategory() ;
I am not sure what you are struggling with, your code is missing a function call to getCategory (should be called getCategories because you are getting plural of objects, not one. Just a sidenote).
Following code is tested and works (save as index.php in your documentRoot to test), please be aware that I cannot declare a function as public when not in a class context, also I could not use $this->_con without a class with _con var, so I used $con instead. You need to adapt it to your context and needs:
index.php:
<?php
$category = filter_input(INPUT_POST,'category');
if($category!=FALSE && $category!=NULL){
$selectedCategory = $category;
}
function getCategory() {
$con = mysqli_connect("localhost","root","","categories") or die("Error " . mysqli_error($con));
echo $query = "SELECT * FROM `categories`";
$results = mysqli_query($con, $query) or die(mysqli_error());
$categories = array();
foreach ($results as $result){
$categories[$result['id']] = $result['category_name'];
}
mysqli_close($con);
return $categories;
}
?>
<html>
<head>
<title>Categories Test</title>
</head>
<body>
<?php
if(isset($selectedCategory)){
echo "last selected category ID: ".$selectedCategory;
}
?>
<form action="index.php" method="POST">
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<?php
$categories = getCategory();
foreach ($categories as $key=>$category): ?>
<option value="<?php echo $key; ?>"><?php echo $category; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="send" />
</form>
</body>
Here is the example i did it in this way. Hope! it will helps you.
public function GetStates()
{
$tempgetstates = mysql_query("SELECT * FROM `states`") or die(mysql_error());
echo '<select name="state" class="sel_reg_form" required />';
echo '<option value="">...Select...</option>';
while($getstates = mysql_fetch_object($tempgetstates))
{
echo '<option value="'.$getstates->state_code.'">'.$getstates->state.'</option>';
}
echo '</select>';
}
I'm trying to create a drop down menu that will select a value that is stored in the database. here's the code :
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if($hasil2) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
the problem is my code creates a dropdown with nothing selected. here's the screenshot : link
i've tried all the solutions in the stackoverflow. but the dropdown value still nothing selected. i know that it has to be something simple that i am missing but seriously i cannot figure it out. please anyone help, thanks!
I think the problem lies in this line:
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
You're missing an echo and it looks funny :/
Try instead:
<option <?php $val=$baris['nama_supplier']; echo "value='$val'"; if($supplier==$val) echo "selected='selected'>";echo $val;?> </option>;
Try this way..
$sel="select f.*,c.category from final f, category c where f.category_id=c.id and f.id='$id'";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
<select name="cat">
<?php
$sql = mysql_query("SELECT * FROM category");
while ($row = mysql_fetch_array($sql)){
if($row['id'] == $res['category_id']){
echo '<option value="'.$row['id'].'" selected="selected">'.$row['category'].'</option>';
}else{
echo '<option value="'.$row['id'].'">'.$row['category'].'</option>';
}
}
?>
</select>
Try this out
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if(mysql_num_rows($hasil2) > 0) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php echo $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) {echo 'selected="selected"';} ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
<option value="<?php $baris['nama_supplier'] ?>
should be
<option value="<?php echo $baris['nama_supplier'] ?>
I spent some time trying to find the best solution for this, and came up with a tiny little jQuery code.
First of all you should be using PDO or mysqli instead of mysql, since it's deprecated. Let's assume you've fixed that.
Inside the <form> tag, add an <input type="hidden"/> so that it can storage your database value, for example:
HTML
<form>
<input id="valueFromDatabase" type="hidden" value="<?php echo $stringFromDB ?>"/>
</form>
Note: in this case, $stringFromDB is a variable that holds your query's return from DB.
So now we have the value of our database inside our HTML code. Now we just need to check if any of the options inside the <select> tag is equal to this value. We'll be doing it with jQuery:
jQuery
$( document ).ready(function() {
$('option').each(function(){
if (this.value == $('#valueFromDatabase').val()){
this.setAttribute('selected', 'selected');
}
});
});
What's happening here? We are telling to jQuery to analyze all the <option> tags in the HTML and compare its value with our value from database; if its equal, we add the selected attribute to the equivalent <option>.
You can it working here (used a calendar example).
Hope that helps!
I have four drop down boxes which display information from the database but it's only displaying two of the four.
http://www.cupboard2stomach.com/php/get.php?dropdown1=bread&dropdown3=chicken&Submit=Submit This is what it currently looks like.
Is there something wrong with my code?
Ingredient 1:<select name= "dropdown1" id = "drop1"/>
<?php
while ($line = mysql_fetch_array($result1, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
Ingredient 2:<select name = "dropdown2" id = "drop2"/>
<?php
while ($line = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
Ingredient 3:<select name = "dropdown3" id = "drop3"/>
<?php
while ($line = mysql_fetch_array($result3, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
Ingredient 4:<select name = "dropdown4" id = "drop4"/>
<?php
while ($line = mysql_fetch_array($result4, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
You are attempting to use XML style self-closing tag syntax for your select elements (<select />) this is wrong and browsers will perform error recovery by ignoring the /.
Consequently, the end tags (</select>) are missing from all your select elements. So you are trying to place your subsequence select elements inside the first one.
Even if you could use self-closing tag syntax on arbitrary elements, the option elements need to be descendants of the select element to which they belong!
A validator would have picked this up for you.
It's because you're not closing your select boxes
For example, change to this:
Ingredient 1:<select name= "dropdown1" id = "drop1"/>
<?php
while ($line = mysql_fetch_array($result1, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
</select>
close your select tag
Ingredient 1:<select name= "dropdown1" id = "drop1"/>
<?php
while ($line = mysql_fetch_array($result1, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
</select>
Ingredient 2:<select name = "dropdown2" id = "drop2"/>
<?php
while ($line = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ingredientname'];?>"> <?php echo $line['ingredientname'];?> </option>
<?php
}
?>
</select>
It is because of select it ends with /> it should end with >
w3c validator gives error
self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.
Next time you should use http://validator.w3.org/ to check your code.
How do I show the selected value of a dropdown list from my mysql database. The dropdown list is dependent to my Category dropdown list. These are the codes:
<?php $id = $_GET["id"];
if(!$pupcon){
die(mysql_error());
}
mysql_select_db($database_pupcon, $pupcon);
$getDropdown2 = mysql_query("select * from tblitemname where CategoryID = $id");
while($row = mysql_fetch_array($getDropdown2)){
echo "<option value=\"".$row["ItemID"]."\">".$row["Item_Name"]."</option>";
} ?>
Here are the codes for the first dropdown list (Category) which populates the Item Name dropdown.
<select name="Category" id="Category" class="field select large" onChange="loadXMLDoc(this.value);">
<?php do { ?>
<option value="<?php echo $row_Recordset1['CategoryID']?>"<?php if (!(strcmp($row_Recordset1['CategoryID'], $row_editRecordset['CategoryID']))) {echo "selected=\"selected\"";} ?>><?php echo $row_Recordset1['CategoryName']?></option>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); $rows = mysql_num_rows($Recordset1); if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);}?>
</select>
While you're listing out the drop down options, you can check to see if the current ItemID matches the passed id value. If it matches, throw a selected="selected" in there. Try:
$selected = ($row['ItemID'] == $id);
echo "<option value=\"".$row["ItemID"]."\" ".($selected ? " selected=\"selected\"":"").">".$row["Item_Name"]."</option>";
EDIT
I tried to clean up the code some...not sure why you're using a do...while because $row_Recordset1 wouldn't be available on the first iteration.
<select name="Category" id="Category" class="field select large" onChange="loadXMLDoc(this.value);">
<?php
while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)) {
?>
<option value="<?php echo $row_Recordset1['CategoryID']; ?>"<?php if (!(strcmp($row_Recordset1['CategoryID'], $row_editRecordset['CategoryID']))) { echo " selected=\"selected\""; } ?>>
<?php echo $row_Recordset1['CategoryName']; ?>
</option>
<?php
}
?>
</select>
you can use this code inside while
$selected=$row["ItemID"]==$id ?'Selected':'';
echo "<option value=\"".$row["ItemID"]."\" {$selected} >".$row["Item_Name"]."</option>";;