Convert select into mysql php input - php

I have an order form where the product is selected from a database with the method "select" and "option". I show screenshot and code
Code:
<div class="form-group">
<select class="form-control" name="productName[]" id="productName<?php echo $x; ?>" onchange="getProductData(<?php echo $x; ?>)" >
<option value="">-- Selecciona --</option>
<?php
$productSql = "SELECT * FROM product WHERE active = 1 AND status = 1 AND
quantity != 0";
$productData = $connect->query($productSql);
while($row = $productData->fetch_array()) {
$selected = "";
if($row['product_id'] == $orderItemData['product_id']) {
$selected = "selected";
} else {
$selected = "";
}
echo "<option value='".$row['product_id']."'
id='changeProduct".$row['product_id']."' ".$selected."
>".$row['product_name']."</option>";
} // /while
?>
</select>
</div>
I would like to transform this way of selecting a product (droping-down list using "select") for an order form in a field that can be input the first letters of the name of the product or reference and I can see in the drop-down list those references that match instead of all references in table. I know that "input" and "post" should be used and in the query to the database something like:
// Conexión a la base de datos y seleccion de registros
$con=mysql_connect("localhost","xxxxx_xxxx","xxxxxxx");
$sql = "SELECT * FROM product WHERE referencia, product_name, position_store
like ‘%$buscar%’ ORDER BY id DESC";
mysql_select_db("xxxxxxx_stock", $con);
$result = mysql_query($sql, $con);
The idea is to do what I show in the screenshot:
Once the matches appear, you can select the one that interests you. I'm not sure how to structure the changes to convert the initial code into what I'm looking for.
I appreciate any help.

Related

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

Using droplist from database set value of another droplist based on the selection of the first one

I have this table
Device Name Price
iPhone 6 300
S8 600
What I am trying to do is have to drop list one that has all the devices Name and the second has an option "Price" but I want to set its value based on the selection of the device name. However, in the drop list it should just display "Price"
I have this php code for the drop lists
$query = "SELECT * FROM `devicehotsheet`";
$options = "";
$result1 = mysql_query($query, $dbhandle);
while ($row1= mysql_fetch_array($result1)){
$options=$options."<option>$row1[0]</option>";
}
For HTML
<select class="selectDevice" id="selectDevice" onChange="calculateTotal()">
<?php echo $options; ?>
</select>
<select class="myport" id="myport" onChange="calculateTotal()">
<option class="price" value=" ">Price</option>
</select>
I have been trying to do this but so far no luck. I would appreciate your help. Thanks
$query = "SELECT * FROM `devicehotsheet`";
$options = "";
$result1 = mysql_query($query, $dbhandle);
while ($row1= mysql_fetch_array($result1)){
$options=$options."<option value='$row1[0]#$row1[1]'>$row1[0]</option>";
}
and the javascript code
function calculateTotal(){
var selDev = document.getElementById('selectDevice').value;
var price = selDev.split('#')[1];
document.getElementById('myport').innerHTML='<option>'+price+'</option>'
}

PHP MYSQL - Drop down select dependant on a previous drop down

As I've tried to describe in the title I have an issue in selecting rows from a MYSQL database depending on the id of another drop down list on the same page. I have only been using mysql and php for 2 months or so now and need help.
I have a table of categories with the below headers.
|id | name | parent_id|
There are parent categories, with a parent_id of 0. And Sub categories with the id of the parent as their parent_id, to a maximum depth of 1 child category. For example:
Software Development is a parent category with id = 18 and parent_id = 0. PHP Developer is a subcategory which has id = 30 and parent_id = 18.
I have a drop down list where I can select the category I work in as follows:
$p_query = "SELECT * FROM categories WHERE parent_id = 0 ORDER by id ASC";
$p_result = mysqli_query($con, $p_query) or die(mysqli_error($con));
$categories ='';
while($p_row = mysqli_fetch_assoc($p_result))
{
$categories .='<option class="option" value="p::'.$p_row['id'].'">' .$p_row['category_name'].'</option>';
}
<select name="categories[]" class="categories form-control" id="categories" style="width:100%" multiple>
<?php echo $categories;?>
</select>
This is working, no problem. However, when I try to get a second drop down list to show the possible categories whom have their parent_id as the id of any selected parent category I retrieve a drop down list with 'No Search Results found'. The code below is what I am using :
$subcategories ='';
while($p_row = mysqli_fetch_assoc($p_result))
{
$c_query = "SELECT * FROM categories WHERE parent_id = ".$categories['id']." ORDER by id ASC";
$c_result = mysqli_query($con, $c_query) or die(mysqli_error($con));
while($c_row = mysqli_fetch_assoc($c_result))
{
$subcategories .='<option class="option" value="c::'.$c_row['id'].'">' .$c_row['category_name'].'</option>';
}
}
<select name="subcategories[]" class="categories form-control" id="subcategories" style="width:100%" multiple>
<?php echo $subcategories ?>
</select>
Is there something that I am missing? As a relative beginner to both PHP and MYSQL, I would be very appreciative of any help or advice.
There is nothing wrong with your second query to retrieve sub-categories based on their parent_id so you're good there. You can test easily like so:
SELECT * FROM categories WHERE parent_id = 1 ORDER by id ASC
How are you providing the value to $categories['id'] as there is nothing in your code creating this array with an 'id' index? Further you already are using a variable called $categories as a string so you shouldn't re-use that variable name without good reason.
Since it appears you want to populate the second multiple select box with subcategories based on the selection of the first you will need to use some javascript+AJAX to submit the second query and write the results in the second selector element.
Using some jquery should help a bit. Try these examples and you'll get the idea.
myselect.php which contains the interface for selecting the category:
<?php
$con = mysqli_connect("host", "username", "password", "database");
$p_query = "SELECT * FROM categories WHERE parent_id = 0 ORDER by id ASC";
$p_result = mysqli_query($con, $p_query) or die(mysqli_error($con));
$categories ='';
while($p_row = mysqli_fetch_assoc($p_result))
{
$categories .='<option class="option" value="p::'.$p_row['id'].'">' .$p_row['category_name'].'</option>';
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous">
</script>
</head>
<body>
Shift or Ctrl + Click to pick more than one<br />
<form id="categoryform" method="POST">
<select name="categories[]" class="categories form-control" id="categories" style="width:100%" multiple>
<?php echo $categories;?>
</select>
</form>
Here's what it contains<br />
<form method="POST">
<select name="subcategories[]" class="categories form-control" id="subcategories" style="width:100%" multiple DISABLED>
</select>
</form>
<script>
$(document).ready(function() {
$('#categories').click(function(){
$('#subcategories').children().remove().end();
var data = $('#categoryform').serialize();
$.post("mysubselect.php", data).done(function(data){
var response = JSON.parse(data);
for (var k in response){
$('#subcategories').append('<option class="option" value="c::' + response[k]['id'] + '">' + response[k]['category_name'] + '</option>');
}
});
});
})
</script>
</body>
</html>
And here's an example of the script returning data from your AJAX request.
mysubselect.php:
<?php
$con = mysqli_connect("host", "username", "password", "database") or die(mysqli_error());
$result = array();
foreach ($_POST["categories"] as $k => $v) {
$category_token = explode('::', $v);
$category_id = mysqli_real_escape_string($con, $category_token[1]);
$query = mysqli_query($con, "SELECT * FROM categories WHERE parent_id = " . $category_id . " ORDER BY id ASC") or die(mysqli_error());
while($r = mysqli_fetch_assoc($query)){
$result[] = $r;
}
}
print json_encode($result);

Second dropdown menu based on value in first (html php mysqli)

I have a MySQL database and am trying make a conditional dropdown menu ("Subcategory") show values based on the values in the first dropdown, ("Category").
This is a reference data table, so the parent ID of the subcategory should match the ref_data_id of the category.
The conditional list relies on the value of the first dropdown box, and I have tried $_POST and $_GET to try to get the value from the first object to use in my MySQLi query but neither seems to work.
Can anyone help?
<?php
// connect to the database
include("connectdb.php");
?>
<html>
<!--First Dropdown Menu - CATEGORIES-->
<div class="label">Select Category:</div>
<select name ="Category_HTML">
<option value = "">---Select---</option>
<?php
$stmt = "SELECT * FROM `ref_data` WHERE Parent_ID IS NULL ;";
$result = mysqli_query($mysqli, $stmt);
while ( $row=mysqli_fetch_array($result)) {
$description = $row['Description'];
$refdataID = $row['Ref_Data_ID'];
echo "<option value='$refdataID'> $description </option>";
}
?>
</select>
<!--Second Dropdown Menu - Subcategory-->
<div class="label">Select Subategory:</div>
<select name="subcategory_HTML">
<option value = "">---Select---</option>
<?php
$idvalue = $_POST['Category_HTML'];
$stmt = "SELECT * FROM `ref_data` WHERE Parent_ID = $idvalue;";
$result = mysqli_query($mysqli, $stmt);
while ( $row=mysqli_fetch_array($result)) {
$description = $row['Description'];
$refdataID = $row['Ref_Data_ID'];
echo "<option value='$refdataID'> $description </option>";
}
?>
</select>
</html>
try to make an AJAX call when a value is select in the category list i.e
<select name ="Category_HTML" onchange="AJAX_CALL()">
and populate the result in the
<select name="subcategory_HTML">

Highlight already selected items in multiple select box

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>

Categories