Hi so the here is my question,
I have a Database containing Categories and Subcategories.
I have two dropdown boxes (select). I want them both to be populated by using PHP/MYSQL.
My Categories have been generated:
<select name="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
I want the subcategories to load when the category has changed.
My SQL will look something like this:
SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'
I need to get the value from the categories dropdown and store it as a variable.
In the past I have done something similar in javascript:
var subcat=document.forms["form"]['subcat'].value;
and then changed the value of another dropdown by calling an onChange(); function like:
document.getElementById('subcat').innerHTML='<option value=""></option>';
I hope someone can point me in the right direction! Should I be looking into AJAX, JavaScript or can it all be done with PHP?
Thank you.
add an id on category select box , like this -
<select name="prod_cat" id="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
for subcategory -
<select id='sub_cat' name='sub_cat'></select>
write your script something like this -
<script>
$("#prod_cat").change(function(){
//get category value
var cat_val = $("#prod_cat").val();
// put your ajax url here to fetch subcategory
var url = 'www.example/fetch_subcategory.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub_cat").html(data);
}
});
});
</script>
add code in ajax calling page -'www.example/fetch_subcategory.php'
<?php
$prod_cat = $_POST['cat_val'];
$sql = "SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg =.'<option value="'. $row["sub_cat_name"] .'">'. $row["sub_cat_name"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo $msg;
mysqli_close($conn);
?>
Do something like this, and hope it will work for you.
Related
How do I echo values that are submitted from a form on another page (which they are submitted into the database) into an HTML tag as options?
This is my latest code and I'm still stuck here. When I clicked on the drop-down list, it still shows nothing.
<select name="comName" id="comName" class="form-control" required>
<?php include('db_company.php');
$query_option = "SELECT * FROM company";
$result = mysqli_query($query_option);
while($row = mysqli_fetch_array($result)) {
echo "<option value='{$row['comName']}'>{$row['comName']}</option>";
}
?>
</select>
There are some mistakes that you have done in here.First of all I would like to suggest you to start using error reporting using,
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
If you have used error reporting from the beginning I believe you would have noticed all the issues that you are facing now.
1.You need to use the DB connection when you are using mysqli_query
$link = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DATABASE);
$result = mysqli_query($link,$query_option);
2.You are using the wrong value inside the while loop.
while($row = mysqli_fetch_array($result)) {
echo "<option>".$row{'company'}."</option>";
}
You are getting comName from the query so you have to use comName instead of company.
while($row = mysqli_fetch_array($result)) {
echo "<option value=".$row{'comName'.">".$row{'comName'}."</option>";
}
Your echo in row is wrong
<?php include('db_company.php');
$query_option = "SELECT * FROM company";
$result = mysqli_query($query_option);
while($row = mysqli_fetch_array($result)) {
echo "<option value='{$row['id']}'>{$row['company']}</option>";
}
?>
My question is that , I want my output is shown in the select tag, in the form of
Dropdown list(treeview Structure) and also i wanted to select multiple categories
with the help of Using html tag i.e, Checkbox.
<?php
function getCategory($parent_id){
$con = connect_db();
$sql = "select ocd.category_id,ocd.name, occ.parent_id from oc_category_description ocd, oc_category occ where ocd.category_id=occ.category_id and parent_id='".$parent_id."' ORDER BY name";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0)
{
echo "<ul>";
while ($row = mysqli_fetch_object($result))
{
echo "<li>".$row->name.'('.$row->category_id.')'."</li>";
getCategory($row->category_id);
}
echo "</ul>";
}
}
$parent_id = 0;
getCategory($parent_id);
?>
Here the output:-
enter link description here
You can show your results in a Dropdown list with these lines of code.Hope this is what you wanted.
if (mysqli_num_rows($result) > 0)
{
echo '<select name="nameUwanted">';
while ($row = mysqli_fetch_object($result))
{
echo "<option value='". $row->name ."'>" .$row->name.'('.$row->category_id.')'."</option>" ;
getCategory($row->category_id);
}
echo "</select>";
}
}
I have no idea why my code isn't working. I basically have two dropdowns, the first is populated from an mssql database and I want the second dropdown to update dependant on the selection in the first.
Below is my code which populates a dropdown box:
<?php
session_start();
$serverName = "REDACTED";
$connectionInfo = array( "Database"=>"REDACTED", "UID"=>"REDACTED", "PWD"=>"REDACTED");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if (!isset($_SESSION['nID']))
{
header("Location: Login.php");
die();
}
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['region']."</option>";
}
return $output;
}
?>
I then use this to populate the first dropdown:
<p>Select a Region
<select name ="region" id ="region">
<option value ="">Select Region</option>
<?php echo loadRegion(); ?>
</select></p>
For the second dropdown box I have the following:
<p>Select a Territory
<select name="territory" id="territory">
<option value="">Select Territory</option>
</select></p>
I call my ajax via:
<script>
$(document).ready(function(){
alert("ready");
$('#region').change(function(){
var region_id = $(this).val();
$.ajax({
url:"getter.php",
method:"POST",
data:{regionId:region_id},
dataType:"text",
success:function(data){
$('#territory').html(data);
}
});
});
});
</script>
My getter page reads as follows:
<?php
session_start();
include 'config.php';
$output = '';
$sql = "SELECT distinct id,territory,rid FROM territoriesHaiss where RID = '".$_POST["regionId"]."' order by id";
$result = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$output = '<option value ="">Select Territory</option>';
while($row = sqlsrv_fetch_array($result))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['territory']."</option>";
}
echo $output;
?>
As pointed out by the 2 comments above (thanks again for the help!) the error was in the code that populates the first dropdown. It should have been a lowercase 'ID', like follows:
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['id'])."\">".$row['region']."</option>";
}
return $output;
}
?>
Hello I have installed jbusinessdirectory component for joomla, and I have module named mod_jbusinessdirectory (this is a search module for business listing) in tmpl/default.php file I have select code: (see below)
<?php if($params->get('showCategories')){ ?>
<div class="select">
<div class="categoryic"></div>
<select name="categorySearch" class="select-styled" id="categories">
<option value="0">category</option>
<?php foreach($categories as $category){?>
<option value="<?php echo $category->id?>" <?php echo $session->get('categorySearch')==$category->id && $preserve?" selected ":"" ?> ><?php echo $category->name?></option>
<?php if(!empty($category->subcategories)){?>
<?php foreach($category->subcategories as $subCat){?>
<option value="<?php echo $subCat->id?>" <?php echo $session->get('categorySearch')==$subCat->id && $preserve?" selected ":"" ?> >-- <?php echo $subCat->name?></option>
<?php }?>
<?php }?>
<?php }?>
</select>
</div>
<?php }?>
From this code I get categories and subcategories like this:
Main category 1
subcategory 1 subcategory 2 subcategory 3
Main category 2
subcategory 1 subcategory 2 subcategory 3
screenshot here: categories and sub categories screenshot
In helper.php I have functions that get categories and subcategories from database
static function getMainCategories(){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__jbusinessdirectory_categories where parent_id=1 and published=1 order by name';
$db->setQuery($query);
return $db->loadObjectList();
}
static function getSubCategories(){
$db = JFactory::getDBO();
$query = ' SELECT c.* FROM #__jbusinessdirectory_categories c
inner join #__jbusinessdirectory_categories cc on c.parent_id = cc.id where c.parent_id!=1 and cc.parent_id = 1 and c.published=1
order by c.name';
$db->setQuery($query,0,1000);
$result = $db->loadObjectList();
return $result;
}
And lastly in modjbusinesdirectory.php file I have the PHP like this:
if($params->get('showCategories')){
$categories = modJBusinessDirectoryHelper::getMainCategories();
if($params->get('showSubCategories')){
$subCategories = modJBusinessDirectoryHelper::getSubCategories();
foreach($categories as $category){
foreach($subCategories as $subCat){
if($category->id == $subCat->parent_id){
if(!isset($category->subcategories)){
$category->subcategories = array();
}
$category->subcategories[] = $subCat;
}
}
}
}
}
categories and subcategories table structure screenshot
here
My question is: How do I make Two select queries instead of one. Where in the first query I get the main categories and in the second query I get the subcategories (eg: if I choose from the first query the main category books and in the second query I choose children it has to show only books with the subcategory children books).
You can use below query for get categories.
function all_cat($id='',$child_of_child='parent')
{
$CI =& get_instance();
if($id="")
{
$query = $CI->db->get_where("__jbusinessdirectory_categories",array('parent_id'=>1));
}
else
{
$query = $CI->db->get_where("__jbusinessdirectory_categories",array('parent_id'=>$id));
}
//echo $CI->db->last_query()."<br>";
$op = '';
if($query->num_rows() > 0)
{
$res = $query->result();
//pr($res);
if($child_of_child == 'child')
{
$op .= '<ul class="sub_cat mrg-top-5" style="display:none;" id="'.$id.'">';
}
else
{
$op .= '<ul class="sub_cat " id="'.$id.'">';
}
foreach($res as $r)
{
$op .= '<li>'.ucwords($r->name).'
</li>';
$op .= all_cat($r->id,$child_of_child='child');
}
return $op .= '</ul>';
}
else
{
return $op;
}
}
It appears that the code already does what you want. You want 2 queries and there are 2. But, I think the result of these 2 queries combines into 1 result and you want to keep it spit into 2 results.
You will have to add new category functions that accept category ID parameters.
<?php
static function getCategoryById($id){
$id = intval( $id );
$db = JFactory::getDBO();
$query = '
SELECT *
FROM #__jbusinessdirectory_categories
WHERE
published=1
AND id= '.$id;
$db->setQuery($query);
return $db->loadObject();
}
static function getChildCategoryList($id){
$id = intval($id);
$db = JFactory::getDBO();
$query = '
SELECT c.*
FROM #__jbusinessdirectory_categories c
INNER JOIN #__jbusinessdirectory_categories cc
ON c.parent_id = cc.id
WHERE c.parent_id!=1
AND cc.id = '.$id.'
AND c.published=1
ORDER BY c.name';
$db->setQuery($query,0,1000);
$result = $db->loadObjectList();
return $result;
}
I am not familiar with Joomla code that retrieves parameters but you can find the ID if you POST it when someone selects a main category.
<?php
if($params->get('showCategories')){
$categoryId = (int) $params->get('mainCategory');
$category = modJBusinessDirectoryHelper::getCategoriesById($categoryId);
$subCategories = modJBusinessDirectoryHelper::getChildCategoryList($categoryId);
}
}
My select consists of two fields and the text field only picks up one of them. Here is my code:
<script>
function ProdValue(data) {
document.getElementById("ProdName").value = data.value;
}
</script>
<select name="ProdName" id="ProdName" onchange ="ProdValue(this)">
<?php
$sql = "Select * from tblProduct";
if ($result = mysqli_query($conn, $sql));
while ($row = mysqli_fetch_assoc($result))
{
echo "<option value='". $row['Brand']."', '".$row['ProductName']."'>".$row['Brand']." ".$row['ProductName']. '</option>';
}
?>
</select>
How can I get ProductName too?
Since your option value contains brand and productname separated by comma, you could do:
function ProdValue(data) {
var optval = data,
prod_name = optval.split(",")[1];
console.log( prod_name ); //here is your product name
document.getElementById("ProdName").value = optval;
}
use this instead. If both columns are actually defined as NOT NULL, CONCAT() will be quite enough:
<?php
$sql = "Select CONCAT(Brand, ProductName) as CombineColumn from tblProduct";
if ($result = mysqli_query($conn, $sql))
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<option value='". $row['CombineColumn']."'>".$row['CombineColumn']."</option>";
}
}
?>