PHP: creating select options from MYSQL database? - php

I'm trying to create multiple select dropdowns from MYSQL database!
basically I need to create select dropdowns based on the given sub-categories and put every op_value related to that sub_cate_name under the created dropdown menu as options.
at the moment, my code creates the dropdowns and select options BUT it will put them in separate select dropdwons and all over the place.
For example: if we have 2 sub_cate_name as Apples and 3 op_value as Reds, Greens, Yellows it will create 2 select dropdown menus and split them op_value which is (Reds, Greens, Yellows) as select options where ever it likes!
but i need it to make sure it creates 1 select dropdown as Apples and put ever op_value related to apples under the Apples dropdown as option!
This is code seems to have mind of its own as it works sometimes and it doesn't others!
this is the entire code:
$drops ="";
$sql44 ="SELECT * FROM drop_options WHERE sub_cat_name='$currentproduct'";
$query44 = mysqli_query($db_conx, $sql44);
$productCount44 = mysqli_num_rows($query44);
if ($productCount44 > 0)
{
$op_name = '';
$first = 0;
while($row44 = mysqli_fetch_array($query44, MYSQLI_ASSOC))
{
$op_value = $row44["op_value"];
if($op_name != $row44["op_name"])
{
if($first)
{
$drops .='</select></div>';
}
$op_name = $row44["op_name"];
$drops .='<div class="col-md-3 col-xs-12">
<p class="margin-bottom-zero">'.$op_name.'</p>
<select name="keyword[]" class="selectpicker">
<option value="'.$op_value.'">'.$op_value.'</option>';
}
else
{
$drops .= '<option value="'.$op_value.'">'.$op_value.'</option>';
}
/*$first = 1;*/
$first++;
}
}
else
{
$drops ='';
}
$drops .='</select></div>';
echo $drops;
Could someone please advise on this issue?
any help would be appreciated.
EDIT:
Okay, now i tried it this way and I can get the exact amount of the select drop downs created as it should:
if($db_conx->connect_errno > 0){
die('Unable to connect to database [' . $db_conx->connect_error . ']');
};
// Perform queries
$sql45 = "SELECT DISTINCT op_name FROM drop_options WHERE sub_cat_name='Custom Booklets";
$result45 = $db_conx->query($sql45);
//echo '<li class="product-types">';
foreach ($result45 as $menu45)
{
// echo "<li>".$menu["cat_name"];
echo '<div class="col-md-3 col-xs-12">
<p class="margin-bottom-zero">'.$menu45["op_name"].'</p>
<select name="keyword[]" class="selectpicker">';
//echo "<ul>";
$menu_title45 = $menu45["sub_cat_name"];
$sql455 = "SELECT * FROM drop_options WHERE op_name='".$menu45["op_name"]."'";
$result455 = $db_conx->query($sq455);
foreach ($result455 as $submenu455)
{
//echo "<li>".$submenu["sub_cat_name"]."</li>";
echo '<option value="'.$submenu455["op_value"].'">'.$submenu455["op_value"].'</option>';
}
echo "</select>";
echo "</div>";
}
//echo "</ul>";
$db_conx->close();
BUT i get no select options created at all Also i get this error: Warning: Invalid argument supplied for foreach() in line 18
and this is on line 18 : foreach ($result45 as $menu45){
any idea what i'm doing wrong?

This is how you're code should look like-
// Perform queries
$sql45 = "SELECT DISTINCT op_name FROM drop_options WHERE sub_cat_name='Custom Booklets'";
$result45 = $db_conx->query($sql45);
//echo '<li class="product-types">';
while ($menu45 = mysqli_fetch_array($result45,MYSQLI_ASSOC))
{
// echo "<li>".$menu["cat_name"];
echo '<div class="col-md-3 col-xs-12">
<p class="margin-bottom-zero">'.$menu45["op_name"].'</p>
<select name="keyword[]" class="selectpicker">';
//echo "<ul>";
$menu_title45 = $menu45["sub_cat_name"];
$sql455 = "SELECT * FROM drop_options WHERE op_name='".$menu45["op_name"]."'";
$result455 = $db_conx->query($sql455);
while($submenu455 = mysqli_fetch_array($result455,MYSQLI_ASSOC))
{
//echo "<li>".$submenu["sub_cat_name"]."</li>";
echo '<option value="'.$submenu455["op_value"].'">'.$submenu455["op_value"].'</option>';
}
echo "</select>";
echo "</div>";
}
//echo "</ul>";
$db_conx->close();
You may want to add if condition to check whether there are actually select options so you wont end up with an empty select.

Related

How Would I Turn Mysqli Table Results into a menu with drop down

Here Is my question: What I am wanting To do is Take Results from a mysql table and turn them into a menu and a drop down menu
HERE IS A QUICK EXAMPLE:
if you see in my mysql table i have page_name and parent, So the example is:
page_name and if i have row 1 the page_name is 'Home' now it's parent is 'none' right but on id number 39 the page_name is 'Contact Us' and the Parent Is 'Far Far Away 123' so if the parent is equal to 'none' then it will show at the top of the menu not the drop down if it has a parent it will show under that parent like this:
Home | the ben page | The Brock Page | Far Far Away 123 | dsfk
Contact Us
You see Contact Us is under Far Far Away Because the parent Is Far Far Away 123
here is my table:
Here is my code That I am trying but it is not working for some reason:
<ul>
<?php
$sql = "SELECT * FROM pages ORDER by item_order";
$result = mysqli_query($db, $sql);
confirm_query($result);
while ($links = mysqli_fetch_assoc($result)) {
if($links['parent'] !== "none") {
?>
<li id = "<?php echo $links['id']; ?>"><a href="
<?php
echo "page.php?id=" . $links['id'] . "\" title=\"" . $links['page_title'] . "\"";
?>>
<?php
echo $links['page_name'];
?>
</a>
<?php
if($links['parent'] !== "none") {
$child = "";
$sql = "SELECT * FROM pages";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result)) {
if($row['parent'] !== "none") {
$child = $row['page_name'];
}
}
echo "<ul id=\"sub_menu\" class=\"sub_navagation" . $links['id'] . "\">";
echo "<li>";
echo $child;
echo "<li>";
echo "</ul>";
}
?>
</li>
<?php
}
}
?>
</ul>
CSS:
#sub_menu {
display: none;
}
#sub_menu:hover {
display: block;
}
Ok if as you can see i have the parent row in the MYSQL table and on id number 39 i want the 'Far Far Away123' to be the parent of Contact Us and i want to show it when i hover over 'Far Far Away123'
My suggestion is to build out an array of all the results. Then run through that array (instead of multiple database queries).
I added a function build_dropdown() that will take the page name and run through the array of pages to see if there are any items with a parent matching. If so, we make an array of those items and run through them to build the dropdown menu. If not, it does nothing and moves on to the next menu item.
<?php
function build_dropdown ($parent, $pages){
foreach($pages as $page){
if($page['parent'] == $parent){
$items = $page;
} // END if
} // END foreach
if(is_array($items)){ // If a sub
echo '<ul id="sub_menu" class="sub_navagation'. $item['id'] .'">';
foreach($items as $item){
echo '<li>'.$item['name'].'<li>';
} // END foreach
echo '</ul>';
} // END if
}
$sql = "SELECT * FROM pages ORDER by item_order";
$result = mysqli_query($db, $sql);
confirm_query($result);
while ($row = mysqli_fetch_assoc($result)) {
$pages[] = $row; // Add each row to $pages array to use later
}
foreach($pages as $key => $page){
if($page['parent'] == 'none'){ ?>
<li id = "<?php echo $page['id']; ?>">
<a href="page.php?id=<?php echo $page['id']; ?>" title="<?php echo $page['page_title']; ?>">
<?php echo $page['page_name']; ?>
</a>
<?php
build_dropdown($page['page_name'], $pages); // If there are child items then build them out
?>
</li>
<?php
} // END if
} // END foreach
?>
I suggest you will need to JOIN your table to basically query it again to get the parent value, and add that to your markup.
SELECT *
FROM Pages
LEFT JOIN Pages p2 on page_name = p2.parent
(note: the syntax above may not be right, but I wanted to give you an idea of where I would start).

Array doesn't appear to be holding data

I have a system where I rearrange navigational items.
It stores the new order in an array and then I use a for loop to go through the array and update the database.
<?php
$apageid = array();
$apagename = array();
$apageorder = array();
$q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order";
$return = $database->query($q);
while($row=mysql_fetch_assoc($return)){
$apageid[] = $row['id'];
$apagename[] = $row['title'];
$apageorder[] = $row['order'];
}
$count = count($apageid);
$bpageid = array();
$bpageorder = array();
?>
<div class="form-holder">
<?php
//run through each page one at a time and update the order of the menu
mysql_data_seek( $return, 0 ); //reset the pointer to do the same query
$i = 0; //the count for saving the new configuration
while($row=mysql_fetch_assoc($return)){
$id = $row['id'];
$title = $row['title'];
$order = $row['order'];
?>
<div class="form-row">
<div class="form-label">
Page Name
</div>
<div class="form-field">
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
<?php
for($j=0; $j<$count; $j++){
if($apageid[$j] == $id) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option>
<?php
}
?>
</select>
<select class="select-small" name="<?php echo $bpageorder[$i]; ?>">
<?php
for($k=0; $k<$count; $k++){
if($apageorder[$k] == $order) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php
$i++;
}
?>
This first chunk of code is the menu where you can reorder items.
Initially it loads up the current select and allows you to change the ordering.
function reorderChildren($pageid, $pageorder){
global $database;
$count = count($pageid);
//run through each page one at a time and update the order of the menu
for($i=0; $i<$count; $i++){
//set a few variables
$pid = $pageid[$i];
$porder = $pageorder[$i];
echo "pid = $pid porder = $porder";
$q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'";
$database->query($q);
}
return 0;
}
The information then ends up being passed here and the problem appears to be the for loop is never executed.
Can anyone see why this would be?
It's not the naming used, I've checked them.
Am I storing information in the arrays correctly?
Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward.
Thanks!
Was a simple fix!
The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned
after that you using
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
but no value is in $bpageid[$i] so name of this select box is blank.
It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display

Reduce number of MySQL Queries and Output Data in Correct Order

My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.

Looping through a drop down, how to select value?

When displaying a form on a page for a user to edit information, and the form consists of a drop down box, how do you loop through the selections in the dropdown box to select their predefined mySQL entry?
For example
Users country: Australia
How would I go about searching through a list of countries ie: http://snipplr.com/view/4792/country-drop-down-list-for-web-forms/ to make:
<option value="AU">Australia</option>
become
<option value="AU" selected="selected">Australia</option>
You could do something like:
<?php
$countries = array('AU' => 'Australia', 'AF' => 'Afghanistan', ...);
$selected = 'AU';
foreach ($countries as $code => $label) {
echo '<option value="' . $code . '"';
if ($selected == $code) {
echo ' selected="selected"';
}
echo '>' . $label . '</option>';
}
?>
Not the prettiest but you get the idea. As Shakti suggests, it's also easier to maintain if the values are in the DB and not in a massive array in the middle of the code.
Could be something like this:
<?php
//your query here
$sql = "SELECT * FROM countries ORDER BY code ASC";
$result_set = $database->query($sql);
while($country = $database->fetch_array($result_set)) {
if ($country["code"] == "AU"){
echo "<option value=\"{$country['code']}\" selected=\"selected\">{$country['name']}</option>";
}
else {
echo "<option value=\"{$country['code']}\">{$country['name']}</option>";
}
?>

combobox treeview in php & mysql

Does anyone know how to display MySQL db hierarchical data (Nested Set Model (http://www.phpro.org/tutorials/Managing-Hierarchical-Data-with-PHP-and-MySQL.html)) in a combo box as shown here under the "Category:" comboxbox field:http://dir.globetourism.biz/submit.php
Thanks
What you need to do is when you print your <option> tags for your combo box you have to check the depth (how to get the depth is in the article that's linked in your question) of each element and print that many "| " strings and another two underscores (__) to give it a nice tree-like look.
<?PHP
function GetCats($id='0',$sublev='0',$vname='C_Parent')
{
$DQ = new MySQLTable;
$DQ -> TblName = 'cat_categories';
$WHERE[$vname]['=']=$id;
$res = $DQ -> Select('C_ID,C_Name',$WHERE,'C_ID');
if (mysql_num_rows($res)>0)
{
while($row = mysql_fetch_assoc($res))
{
$ss='';
if($sublev!=='0')
{
for($i=0;$i<=$sublev*10;$i++)
{
$ss.=' ';
}
$ss.='|';
for($i=0;$i<=$sublev;$i++)
{
$ss.='-';
}
$ss.='>>';
}
$sel_s = '';
if(IsSet($_POST['C_Parent']))
{
if($row['C_ID']==$_POST['C_Parent'])
{
$sel_s = ' selected';
}
} elseif (IsSet($_POST['I_Parent'])) {
if($row['C_ID']==$_POST['I_Parent'])
{
$sel_s = ' selected';
}
} else {
$sel_s = '';
}
Echo "<option value=\"".$row['C_ID']."\" ".$sel_s.">".$ss.$row['C_Name']."</option>\r\n";
GetCats($row['C_ID'],$sublev+1);
}
}
}
Echo "<select name=\"C_Parent\">\r\n";
Echo "<option value=\"0\">...</option>\r\n";
GetCats();
Echo "</select>";
?>
Something like this.
But here was my own MySQL class. The query is: SELECT C_ID,C_Name WHERE C_Parent=$id ORDER BY C_ID where $id - php variable (current parent cat).
And there are $_POST variables if error submit to store selected.
This is not the most effective way to di it bcoz many queries. More effectively is to get all data to array to work with.

Categories