Highlight already selected items in multiple select box - php

I have 2 tables one 'brand' that stores all the brand names and 'brand_category' that stores all the brand names with their corresponding categories. I have a multiple select box that loads all the items in the 'brand' table when the page loads, but I need to highlight the items that are already submitted by the user previously in the 'brand_category' table with the rest of the brands that are left so that the user knows what are the brands left to be entered in the 'brand_category' table. Below is the code but it doesn't work. Please help to resolve this issue
<div class="selectbox">
<label id="brand" class="brand_label">Brand:</lable>
<?php
echo "<select name='brand' class='cat_brands' multiple>"
<option value='0'>None</option>";
$query = mysql_query("SELECT id, name FROM brand");
while($br_query = mysql_fetch_assoc($query)){
$query_select = mysql_query("SELECT * FROM brand_category WHERE brand_id='".$br_query['id']."'");
while($brnd_select = mysql_fetch_assoc($query_select)){
if($brnd_select['brand_id']==$br_query['id']){
echo "<option style='background-color: red' value='".$br_query['id']."'>".$br_query['name']."</option>";
}
}
}
?>
</div>
The above code only displays the brands entered in the 'brand_category' table rest of the brands are not displayed. I need to display them also.

You forgot to mention else condition inside while loop.Here is the code
<div class="selectbox">
<label id="brand" class="brand_label">Brand:</lable>
<?php
echo "<select name='brand' class='cat_brands' multiple>"
<option value='0'>None</option>";
$query = mysql_query("SELECT id, name FROM brand");
while($br_query = mysql_fetch_assoc($query)){
$query_select = mysql_query("SELECT * FROM brand_category WHERE brand_id='".$br_query['id']."'");
while($brnd_select = mysql_fetch_assoc($query_select)){
if($brnd_select['brand_id']==$br_query['id']){
echo "<option style='background-color: red' value='".$br_query['id']."'>".$br_query['name']."</option>";
}else{
echo "<option value='".$br_query['id']."'>".$br_query['name']."</option>";
}
}
}
?>
</div>

If I have understood your query correctly you are trying to pull out all the brands and to make the ones in the brands_category table to display as selected.
You should better be using MySQL PDO extensions rather than this obsolete method
There are better ways to implement this, e.g. by having just one table or by using a Join query, anyway... this should work.
<select name='brand' class='cat_brands' multiple>
<option value='0'>None</option>
<?php
$query = mysql_query("SELECT id, name FROM brand");
while($br_query = mysql_fetch_assoc($query))
{
$query_select = mysql_query("SELECT * FROM brand_category WHERE brand_id='".$br_query['id']."'");
if(mysql_num_rows($query_select) > 0)
{
while($brnd_select = mysql_fetch_assoc($query_select))
{
echo "<option style='background-color: red' value='".$br_query['id']."' selected='selected'>".$br_query['name']."</option>";
}
}
else
{
echo "<option style='background-color: yellow' value='".$br_query['id']."'>".$br_query['name']."</option>";
}
} ?>
</select>

Related

Brand_title is not saved in database?

I am making an insert mobile data page where for brands i had made dropdown menu the dropdown menu is working perfectly but when I insert mobile data brand id is inserted in database but brand title is not inserted why?
// code for dropdown menu
<tr>
<td style="color:#fff"><b>Mobile Brand</b></td>
<td>
<select name="Mbrand">
<option>Select Brand</option>
<?php
$get_brands = "select * from brands";
$run_brands = mysqli_query($con, $get_brands);
while ($row_brands=mysqli_fetch_array($run_brands))
{
$brand_id = $row_brands['brand_id'];
$brand_title = $row_brands['brand_title'];
echo "<option value='$brand_id'>'$brand_title'</option>";
}
?>
</select>
</td>
</tr>
----------------------------
// code for defining data
<?php
if(isset($_POST['insert_mobile'])){
//text data variables
$mobile_title=$_POST['Mname'];
$mobile_price=$_POST['Mprice'];
$mobile_brand=$_POST['Mbrand'];
$mobile_desc=$_POST['mdesc'];
$mobile_keywords = $_POST['key'];
-----------------------------
//code for inserting data
$insert_mobile = "insert into mobile_phone (mobile_name,brand_id,date,price,img1,img2,img3,mobile_desc,product_keywords) values ('$mobile_title','$mobile_brand',NOW(),'$mobile_price','$mobile_img1','$mobile_img2','$mobile_img3','$mobile_desc','$mobile_keywords')";
$run_mobile= mysqli_query($con,$insert_mobile);
if($run_mobile)
{
echo "<script>alert('mobile added successfully')</script>";
exit();
}
Please try using $brand_title instead of $brand_id in the option value.
echo "<option value='$brand_id'>'$brand_title'</option>";
will become
$brand = $brand_id.':'.$brand_title;
echo "<option value='$brand'>'$brand_title'</option>";
Edit
Option value is actually the one that gets passed in $_POST[] values and that can be stored in database as you need.
Edit
Replace the below code
$mobile_brand=$_POST['Mbrand'];
with
$brand_id = explode(':', $_POST['Mbrand'])[0];
$brand_title = explode(':', $_POST['Mbrand'])[1];
And please change the Insert query accordingly, so that it can accomodate or store both brand_id and brand_title in respective columns. Please check the datatypes of those columns before you run the script.

foreach inside while loop

I have 2 tables in my DB - Categories and Products.
In products table, I am using a foreign key field named category_id which contains comma separated category ids to which that product belongs to.
Now I am using a multi select drop down using which the admin can select multiple categories for which that product belongs to.
Now while editing the product, I want to display all the categories from categories table along with the selected categories for that particular product should be marked as selected.
My query is something like below but my problem is that it repeats the categories values multiple times. I dont want to repeat the values. Any help would be appreciated.
<?PHP
$query_product = "SELECT * from cmco_products where product_id=$product_id";
$res_product = mysqli_query($conn, $query_product) or die(mysqli_error($conn));
$numrows = mysqli_num_rows($res_product); //check if the record existis into the DB
if($numrows > 0) //if the record exists into the DB
{
$row_product = mysqli_fetch_object($res_product);
$cat_id = explode(",", $row_product->category_id);
?>
<select class="form-control show-tick" name="multi_categories_id" id="multi_categories_id" multiple>
<?php
$query_categories = "SELECT * from cmco_categories order by date_created desc";
$res_categories = mysqli_query($conn, $query_categories) or die(mysqli_error($conn));
$x = 1;
while($row_categories = mysqli_fetch_array($res_categories))
{
foreach($cat_id as $key => $val)
{
$vals[$key] = trim($val)."<br />";
$qry_cat = "SELECT * from cmco_categories where category_id =".trim($val);
$res_cat = mysqli_query($conn, $qry_cat) or die(mysqli_error($conn));
$row_cat = mysqli_fetch_array($res_cat);
?>
<option value="<?php echo $row_categories['category_id']; ?>" <?php if($row_categories['category_id'] == trim($val)) { echo "selected";} ?>><?php echo $row_categories['category_name']; ?></option>
<?php
}
}
?>
</select>
<?PHP
}
?>
Thanks

getting a selection box to set a default value using the latest value in a mysql database

Need some help on this PHP and MySQL query.
The selection box gets populated properly but for selecting the current set default value I cant seem to get the if statement it to work. been trying to find an answer everywhere to this question but cant seem to get it.
What I'm trying to do is to just select the latest row from the table TOP and to see if the field BRAND equals the SN field from the table BRANDS
hope someone can shed some light on my failings here cause I'm doing my head in.
<select name="top">
<?php
$query = $db->query("SELECT * FROM BRANDS");
$querytop = $db->query("SELECT MAX(NUM) FROM TOP");
$rtop = $querytop->fetch_object();
while($row = $query->fetch_object()){
if ($row->SN == $rtop->BRAND){
echo "<option value='".$row->SN."' selected=\"selected\">".$row->BRAND."</option>";
}else{
echo "<option value='".$row->SN."'>".$row->BRAND."</option>";
}
}
?>
</select>
EDIT1:
Here's the HTML I'm getting; the $rtop->BRAND does not return a value. therefore the if statement is always false, even if it; logically speaking, should return true.
<select name="top">
<option value='21'>asd</option>
<option value='22'>Test1</option>
</select>
I think, this shoud help you:
$querytop = $db->query("SELECT MAX(NUM) FROM TOP");
change to:
$querytop = $db->query("SELECT MAX(NUM) AS BRAND FROM TOP");
Please Try This type..:)
if ($row->SN == $rtop->BRAND){
echo "<option value='{$row->SN}' selected=\"selected\">"{$row->BRAND}"</option>";
}else{
echo "<option value='{$row->SN}'>"{$row->BRAND}"</option>";
}
the problem I faced was that I was only selecting the NUM field when im actually trying to find the BRAND value from the num field.
the correction
$querytop = $db->query("SELECT BRAND FROM toppage WHERE NUM=(SELECT max(NUM) FROM toppage)");
the code in full
<?php
$query = $db->query("SELECT * FROM BRANDS");
$querytop = $db->query("SELECT BRAND FROM toppage WHERE NUM=(SELECT max(NUM) FROM toppage)");
$rtop = $querytop->fetch_object();
while($row = $query->fetch_object()){
if ($row->SN == $rtop->BRAND){
echo "<option value='$row->SN' selected=\"selected\">".$row->BRAND."</option>";
}else{
echo "<option value='$row->SN'>".$row->BRAND."</option>";
}
}
?>

mysqli join two tables to match user name with the corresponding user id

I'm having a hard time figuring this out..
I have two tables "teacher_info" and "section_info".
In my forms I included all the attributes in my section_info table except I used teacher name instead of teacher id for easy selection which is a dropdownlist of teacher's name, this is my code
<?php
include("anhsis.php");
mysqli_select_db($con,"anhsis");
$result= mysqli_query($con,"SELECT t_lname,t_fname FROM teacher_info");
echo"<select name='adviser' class='form-control' required>";
echo"<option value='0'>--Select Adviser--</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value='".$row['t_lname']."".$row['t_fname']."'>".$row['t_lname'].", ".$row['t_fname']."</option>";
}
echo'</select>'
?>
and heres my php code to insert data in "section_info"
<?php
include_once('anhsis.php');
$room_id = $_POST['room_id'];
$section = $_POST['section'];
$adviser = $_POST['teacher_id'];
$level = $_POST['level'];
$curriculum = $_POST['curriculum'];
mysqli_select_db($con,"anhsis");
$result= mysqli_query($con,"SELECT * FROM section_info WHERE room_id= '$room_id'");
if (mysqli_num_rows($result)>0){
echo '<script type="text/javascript">';
echo 'alert("TIN No already exist!")';
echo '</script>';
}
else{
mysqli_query($con,"INSERT INTO section_info VALUES('$room_id','$section','$adviser','$level','$curriculum')");
}
?>
my problem is that in my section_info theres no attribute of teacher's name, instead it has teacher_id. So how am I going to insert teacher_id from the "teacher_info" table to the "section_info" table by just selecting the teacher's name in my dropdownlist. Or is it possible?
Thanks!
$result= mysqli_query($con,"SELECT t_lname,t_fname,teacher_id FROM teacher_info");
echo "<select name='adviser' class='form-control' required>";
echo "<option value='0'>--Select Adviser--</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value='".$row['teacher_id']."'>".$row['t_lname'].", ".$row['t_fname']."</option>";
}
This way you will have teacher_id value in $adviser variable, ready to use.

Make mysql query connect to the selected table in a drop down menu

I have a working mysql query that retrieves data from table1.
Now I will add every month a new table (table2, table3..etc).
Goal 1 : I would like to add a drop down menu and populate it with all tables as user options.
Goal 2 : I would like to make the query connect to the table that the user selects from the drop down menu, retrieves data and then refresh the page or just the table's div to display updated data.
my current mysql/php code :
$query = "SELECT X, Y, Z FROM **table1**";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['X'];
echo $row['Y'];
echo $row['Z'];
}
Instead of "table1" it should be a variable linked to the drop down menu that the user selects.
I feel it should be simple, but I am bit new to this and could not find a similar case.
Thanks a lot gents.
I like the comment above but here is an example not sure if that what you are looking for
<form action="process.php" method='post'>
<select name="tables">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" />
</form>
process.php file
$table=$_POST['tables'];
$query = "SELECT X, Y, Z FROM ".$table;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['X'];
echo $row['Y'];
echo $row['Z'];
}
$result = 'SHOW TABLES [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr];';
while($row = mysql_fetch_array($result))
{
echo $row['Tables_from_db_name'];
}

Categories