How to output product variations - php

I would like some advice on how best to approach outputting multiple products and their variations from a database.
I am building an eCommerce application and need to output a series of products and their product variations (colour, size).
My database has:
Table 1: ProductID, ProductTitle, ProductImg, ProductCat
Table 2: ProductID, ProductSize, ProductColour
Foreign key on ProductID
My current code is this:
<?php
$q = $_GET['cat']; // this pulls the category from URL param
include 'db_connect.php';
$result = mysqli_query($con, "SELECT DISTINCT a.ProductTitle, a.ProductImg, b.ProductColour
FROM product_info AS a
JOIN product_options AS b ON a.ProductID=b.ProductID
WHERE a.ProductCat = '".$q."'");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<div class='product-display'>";
echo "<img id='prodImage' src='Images/" . $row['ProductImg'] . ".jpg' alt='product photo'>";
echo "<h3>" . $row['ProductTitle'] . "</h3>";
echo "<h3>" . $row['ProductColour'] . "</h3>";
echo "</div>";
}
?>
This outputs:
Product 1, Colour 1
Product 1, Colour 2
Product 2, Colour 1
Product 2, Colour 2
Product 3, Colour 1
Product 3, Colour 2
I want it to output:
Product 1, Colour 1, Colour 2
Product 2, Colour 1, Colour 2
Product 3, Colour 1, Colour 2
What is the best way to achieve this?
FYI - my array output is this:
Array ( [ProductTitle] => Puffer Jacket [ProductImg] => 444 [ProductColour] => Aubern )
Array ( [ProductTitle] => Puffer Jacket [ProductImg] => 444 [ProductColour] => Black )
Array ( [ProductTitle] => The Bander [ProductImg] => 111 [ProductColour] => Aubern )
Array ( [ProductTitle] => The Bander [ProductImg] => 111 [ProductColour] => Black )
Array ( [ProductTitle] => The comfy one [ProductImg] => 222 [ProductColour] => Aubern )
Array ( [ProductTitle] => The comfy one [ProductImg] => 222 [ProductColour] => Black )
SOLUTION:
Please refer to:
Parsing one col of multiple rows php
and
SQL JOIN - Need to return one product id but all variations of it (e.g. Size, colour)
These answer it nicely... problem solved.

Related

SQL how do I join two tables using prepared statements based on values found in an array

I have the table products which contains the following:
product_id | name | category | img
1 car toy tcar.jpg
2 boat toy tboat.jpg
3 plane actual plane.jpg
I also have the table product which contains the following:
product_id | size | price
1 large 5
2 small 3
2 medium 4
3 small 7
Finally, I have a multidimensional array called $products_in_cart, with key equal to product_id. It stores the following values:
Array ( [1] => Array ( [Quantity] => 1 [Size] => large) [2] => Array ( [Quantity] => 5 [Size] => medium ) )
I want to inner join products and product and then fetch the products which are found in the array $products_in_cart. (so I will fetch based on the product_id (the keys in $products_in_cart) as well as the size). This has to be done using prepared statements.
I managed to fetch products which are found in $products_in_cart using these statements:
$array_to_question_marks = implode(',', array_fill(0, count($products_in_cart), '?'));
$stmt = $pdo->prepare('SELECT * FROM products WHERE product_id IN (' . $array_to_question_marks . ')');
$stmt->execute(array_keys($products_in_cart));
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
This gives the output:
Array ( [0] => Array ( [product_id] => 1 [name] => car [category] => toy [img] => tcar.jpg) [1] => Array ( [product_id] => 2 [name] => boat [category] => toy [img] => tboat.jpg))
However, what I want is to get this output:
Array ( [0] => Array ( [product_id] => 1 [name] => car [category] => toy [img] => tcar.jpg [size] => large [price] => 5) [1] => Array ( [product_id] => 2 [name] => boat [category] => toy [img] => tboat.jpg [size] => medium [price] => 4))
I expect that I should inner join products and product and then pick those with id's and size that match the ones in $products_in_cart. However I got no clue on how to do that (prepared statements are making the process complicated for me).
I'm sorry for my poor description of the problem, but I hope that the example of what I managed to do makes it clear, thanks!
Well, if you want to do a inner join, just... do an inner join. Nothing says you can't do one within a prepared statement!
Replace this line
$stmt = $pdo->prepare('SELECT * FROM products WHERE product_id IN (' . $array_to_question_marks . ')');
With this one (I'm spliting it in lines for better clarity):
$stmt = $pdo->prepare('SELECT * FROM products
INNER JOIN product
ON (products.product_id = product.product_id)
WHERE products.product_id IN (' . $array_to_question_marks . ')');
You could also use the "shorthand" version if you prefer:
$stmt = $pdo->prepare('SELECT * FROM products, product
WHERE products.product_id = product.product_id
AND products.product_id IN (' . $array_to_question_marks . ')');
As a side note, using two similar named tables is confusing. Since the "product" table contains sizes and prices and no product information, you could rename it to something like "prices_sizes" or something like that.

how to make combination of product variants in php via user input

I'm creating multiple product variant's where user creates options for the product and and add values to options. after that when adding a product user select options for the product such as color, size or or for mobile ram, color, storage with fixed options quantity and price. I have created the database for it but i am unable to bind the variants related to product as per user input. As i m doing this in simplest form of php without oop concept but i am unable to do this
i have already tried using array. but unable to bind the options like :-
options
option_id option_name
1 Size
2 Color
3 Ram
4 Inch
5 Storage
option_values
value_id option_id value_name
1 1 S
2 1 M
3 1 L
4 2 Red
5 2 Black
6 3 4GB
7 3 8GB
8 5 500GB
products_variants
product_id option_id value_id sku_var
1 1 2 SKU_a1
1 1 2 SKU_a2
1 2 4 SKU_a1
1 2 5 SKU_a2
sku_variant_vlaues
quantity price sku_var
5 100 SKU_a1
8 120 SKU_a2
// Posting data using php
// FIXED Options
$product_quantity = isset($_POST['product_quantity ']) ? $_POST['product_quantity '] : '0';
$product_price = isset($_POST['product_price']) ? $_POST['product_price'] : '0';
/---------------------- OTHER VARIANT -------------------/
// this variable is ($all_options_filled) where user chooses which option to be added in product variant like color, size, ram, storage, inch, width etc.
in this variable all the input field name are stored as field1, field2, field3
foreach($all_options_filled as $aof_field_name){
if(!empty(trim($aof_field_name))){
$other_options = $con->query("SELECT `option_id`, `option_key`, `option_name` FROM `options` WHERE `option_key`='".$aof_field_name."' AND `status`='ACTIVE' ORDER BY `position` ASC LIMIT 1");
if($other_options->num_rows>0){
$row_other_options=mysqli_fetch_array($other_options);
$roo_option_id= $row_other_options['option_id'];
$roo_option_key = $row_other_options['option_key'];
$roo_option_name = $row_other_options['option_name'];
$multiple_option_name[] = isset($_POST[$roo_option_key]) ? $_POST[$roo_option_key] : ''; // array + multiple fields ## multiple array
$multiple_option_id[] = $roo_option_id; // all posted fields id's
}
}
}
/---------------------- OTHER VARIANT -------------------/
after inserting product data ->
getting the latest id of product as a ( $product_latest_id )
and sku id and sku title as per product as a ( $sku_latest_id , $sku_title )
below i am inserting the variants
if(!empty($multiple_option_name)){ // this variable came from other variants - those are created by user
//foreach($multiple_option_name as $one_multiple_option){
//var_dump($multiple_option_name);
for($i=0; $i<=sizeof($multiple_option_name)-1; $i++){
$multiple_option_name_1 = $multiple_option_name[$i];
$single_option_id = $multiple_option_id[$i];
if(!empty($multiple_option_name_1)){
//var_dump($one_multiple_option); echo "<br>";
if(!empty($multiple_option_name_1)){
//foreach($multiple_option_name_1 as $one_option_value){
//var_dump($one_option_value); echo "=> $single_option_id <br>";
for($j=0; $j<=sizeof($multiple_option_name_1)-1; $j++){
$one_option_value = $multiple_option_name_1[$j];
if(!empty($one_option_value)){
$get_one_option_value_id = $con->query("SELECT `value_id` FROM `option_values` WHERE `option_id`='".$single_option_id."' AND `value_name`='".$one_option_value."'");
if($get_one_option_value_id->num_rows>0){
list($g_option_value_id)=mysqli_fetch_array($get_one_option_value_id);
}else{
$goov_get_page_number=mysqli_query($con,"SELECT max(`position`) as position FROM `option_values` WHERE `option_id`='".$single_option_id."' ORDER BY `value_id` DESC LIMIT 1");
if($goov_get_page_number->num_rows==1){
$goov_row_pos = mysqli_fetch_array($goov_get_page_number);
$goov_position = $goov_row_pos['position']+1;
}else{
$goov_position = 1;
}
$create_one_option_value_id = $con->query("INSERT INTO `option_values`(`option_id`, `value_name`, `position`, `status`) VALUES
('".$single_option_id."', '".$one_option_value."', '".$goov_position."', 'ACTIVE')");
$get_latest_one_option_value_id = $con->query("SELECT `value_id` FROM `option_values`
WHERE `option_id`='".$single_option_id."' AND `value_name`='".$one_option_value."' AND `position`='".$goov_position."' AND `status`='ACTIVE'");
list($g_option_value_id)=mysqli_fetch_array($get_latest_one_option_value_id);
}
$sku_var = $sku_title."-$product_latest_id-$single_option_id-$g_option_value_id";
$insert_product_variant_values = $con->query("INSERT INTO `product_variant_values`(`product_id`, `option_id`, `value_id`, `value`, `sku_var`) VALUES
('".$product_latest_id."', '".$single_option_id."', '".$g_option_value_id."', '".$one_option_value."', '".$sku_var."')");
$p_quantity = $product_quantity[$j];
if($p_quantity>0){
$is_quantity_stock = 1;
}else{
$is_quantity_stock = 0;
}
$p_show_price = $show_price[$j];
$p_variant_currency = $admin_currency_code; // product currency
$p_price = $product_price[$j];
$p_variant_status = "ACTIVE";
$insert_sku_variant_vlaues = $con->query("INSERT INTO `sku_variant_vlaues`(`sku_id`, `product_id`, `sku_var`,
`stock`, `is_stock`, `show_price`, `currency`, `price`, `status`) VALUES ('".$sku_latest_id."', '".$product_latest_id."', '".$sku_var."',
'".$p_quantity."', '".$is_quantity_stock."', '".$p_show_price."', '".$p_variant_currency."', '".$p_price."', '".$p_variant_status."') ");
}
}
}
}
}
}
below is the table structure used for database:
product table -
product_id
product_name
Sku table-
sku_id
sku_title
product_id
options table -
option_id
option_key // used as input field name in front id
option_name
option values table-
value_id
option_id
value_name
product_variant_values table -
product_variant_value_id
product_id
option_id
value_id
sku_var -> // i am using this by adding (sku title, product_id, option_id and value_id) to match it unique to (sku_variant_vlaues table) so i can identify which option is used for which quantity and price
sku_variant_vlaues table -
id - primary key
sku_id
product_id
sku_var -> same sku value from (product_variant_values) table
quantity
price
$postData = array();
// $option_id you need to pass option value i create array so i print key you need to print object which contain the id of the option'
$option_array = [1 => 'Size' , 2=> 'Color'];
foreach ($option_array as $option_id => $value) { ?>
<input type="checkbox" name="option_type_id[<?php echo $option_id?>]" value="1">
<?php
}
$i = 0;
foreach ($option_array as $key => $option_type) {
$postData['option_type_id'][$key] = array();
$i++;
$array = $option_values[$key];
foreach ($array as $option_value_id => $value) {
$postData['option_type_id'][$key][] = $option_value_id;
?>
<input type="checkbox" name="option_type_id[<?php echo $key?>][option_values][]" value="<?php echo $option_value_id?>">
<?php }
}
$variants_data = array();
$lastInsertedProductId = 1;
$lastInsertedProductSKU = "SKU1";
foreach ($postData['option_type_id'] as $key => $value) {
foreach ($value as $option_id => $option_value) {
$variants_data[] = array(
'product_id' => $lastInsertedProductId,
'sku_var' => $lastInsertedProductSKU,
'option_id' => $key,
'option_value' => $option_value,
);
}
}
// it produce out put like this
Array
(
[0] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 1
[option_value] => 1
)
[1] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 1
[option_value] => 2
)
[2] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 2
[option_value] => 4
)
[3] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 2
[option_value] => 6
)
)
echo "<pre>";print_r($variants_data);die;
//So now you can simple check the output is matched according your database
when you post this inputs your functionality will work like this hope this will solve your problem

How to generate a query using an array of delimited columns & values

I have this array:
$filter=['color*black','color*blue','color*red','paint*apex','paint*dalton'];
Each value in $filter has two substrings separated by *. The first substring represents a database table column and the second represents a desired value for that column.
My products table looks like this:
id name color paint
1 p1 black compo
2 p2 red dalton
3 p3 pink apex
4 p4 blue apex
5 p5 cream compo
Using $filter, I need to search the products table and return all rows with a paint value of apex or dalton AND a color value of black, blue, or red.
The desired output is a mysql query that will only return these rows:
id name color paint
2 p2 red dalton
4 p4 blue apex
If You need to construct a query like this SELECT * FROM products WHERE (color IN ('black', 'blue', 'red')) AND (paint IN ('apex', 'dalton')), then the code below might be useful (please, check it here):
$filter = array(
0 => "color*black",
1 => "color*blue",
2 => "color*red",
3 => "paint*apex",
4 => "paint*dalton"
);
$elements = [];
foreach ($filter as $value) {
list($before, $after) = explode('*', $value);
$elements[$before][] = $after;
}
$parts = [];
foreach ($elements as $column => $values) {
$parts[] = "(`$column` IN ('" . implode("', '", $values) . "'))";
}
$query = 'SELECT * FROM `products` WHERE ' . implode(' AND ', $parts);
Running this query against the given table data structure:
id name color paint
1 p1 black compo
2 p2 red dalton
3 p3 pink apex
4 p4 blue apex
5 p5 cream compo
will match the following rows:
2 p2 red dalton
4 p4 blue apex
Here we are using explode, foreach and array_values to achieve desired output.
Try this code snippet here
<?php
$filter = array(
0 => "color*black",
1 => "color*blue",
2 => "color*red",
3 => "paint*apex",
4 => "paint*dalton");
$result=array();
foreach($filter as $value)
{
list($before,$after)=explode("*",$value);
$result["before"][$before]=$before;
$result["after"][$after]=$after;
}
$result["before"]= array_values($result["before"]);
$result["after"]= array_values($result["after"]);
print_r($result);
Output:
Array
(
[before] => Array
(
[0] => color
[1] => paint
)
[after] => Array
(
[0] => black
[1] => blue
[2] => red
[3] => apex
[4] => dalton
)
)

PHP Need Help In Sub Array

I have a two table 1. grocery_product and 2. grocery_attribute where i can get all data from grocery_product my array look like as below.
Array
(
[0] => Array
(
[id] => 1
[pname] => Royal Moong Dal/Moong Dal
[categoryid] => 4
[subcatid] => 3
[added_date] => 2016-08-16
)
[1] => Array
(
[id] => 2
[pname] => Royal Toor Dal/Arhar Dal/Tuver Dal
[categoryid] => 4
[subcatid] => 3
[added_date] => 2016-08-16
)
)
What i want to do that in my grocerry_attribute table i am passing grocery_product_id and fetch all data from grocery_attribute where product is only one and attributes are multiple.
My grocery atrtribute table look like .
id 1
product_id 2
price 1500
discount 15
product_qty 20
id 2
product_id 2
price 1000
discount 10
product_qty 50
i want to fetch one grocery_product(id=1) and its attribute data.
Query ??
You can use LEFT JOIN like,
SELECT p.id,p.pname,g.price,g.discount,g.product_qty FROM
grocery_product as p
LEFT JOIN grocery_attribute as g
ON p.id = g.product_id
WHERE p.id=2
Now you can loop for attributes and show different price, discount, and product_qty for a single product.
// Let $products is multidimensional array
if(!empty($products) && isset($products[0]['pname'])){
echo '<h1>'.$products[0]['pname'].'</h1>';
foreach($products as $product){
echo 'Price:'.$product['price']."\n";
echo 'Discount:'.$product['discount']."\n";
echo 'Product Quantity:'.$product['product_qty']."\n";
}
}

retrive data from session and save to mysql

I want to create a simple shopping cart, but i can't save the data from cart session.
Example:
product_code | qty
Orange | 10
Apple | 5
I want to get orange quantity but it always get the latest one qty(apple)
Here is the value of $_SESSION['products']:
Array
(
[10] => Array
(
[product_qty] => 2
[kode_produk] => 10
[nama_produk] => Rainbow Cake
[harga] => 75000
[gambar] => rainbow.jpg
)
[15] => Array
(
[product_qty] => 3
[kode_produk] => 15
[nama_produk] => Black Forest
[harga] => 100000
[gambar] => black.jpg
)
)
Here is my code:
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
foreach($_SESSION["products"] as $product){ //Print each item, quantity and price.
$product_name = $product["nama_produk"];
$product_qty = $product["product_qty"];
$product_price = $product["harga"];
$product_code = $product["kode_produk"];
$_SESSION['kode_produk'] = $product_code;
$jumlah = $_SESSION['product_qty'];
$foto=$product["gambar"];
$asu= $_SESSION["sssdasd"];
$sql1 = ' insert into detail_pemesanan
(kode_produk,jumlah)
values
("'.$product_code.'","'.$product_qty.'");
';
$query = mysqli_multi_query($mysqli_conn,$sql1);
}
}
but it always ended like this
Orang 10
Apple 10

Categories