Fetching association with selected options in dropdown PHP CART - php

When i select a product in my gallery it goes to my cart.
I get my product id and store them in a session.
And in my cart i got to select size and which fabric i want to order my product.
My product is cushion.
My cart.php has all function to make the cart session work,
and has all the buttons functions too.
I display my selected products in my page checkout.php ... i call my cart function in that page...
To select size and fabric i have 2 dropdowns, the size dropdown is static html options, and my fabrics are getting data from my DB.
Look this image before...
As you see i got these two tables.
When i select my fabric and it size i want to fetch the value in the fabrics prices table.
My cart a got a session where it grabs the user state.
If the user is in the same state that i am,the price of the fabric will be one cost else it will be other cost.(IN_state,Out_state columns).
My QNTD row in the cart table is quantity $value
Valor is value of costs in pt-br.
A bad thing is that my dropdown dont save the selected option.
lets say that i selected a fabric Velvet and size 50x50.
And i click on add or less button my page will refresh and all options will be lost.
What i did is store the selected option using LocalStorage.
It works only for the first row in the checkout.
How can i get all these data to work with out submitting something.
Maybe i can use more sessions to get all data and make the calculation.
But im a bit lost in all this.
What can i do to get this working all together ?
my cart code..
<?php
include_once '../incluedes/conn_cms.php';
// gets the product id from gallery and store in session and add +1
if(isset($_GET['add'])){
$select = "SELECT * FROM gallery2 WHERE id=" . escape_string($_GET['add'])." ";
$run_selection = mysqli_query($conn,$select);
while($rows = mysqli_fetch_assoc($run_selection)){
if($rows['id'] != $_SESSION['product_'.$_GET['add']]){
$_SESSION['product_' . $_GET['add']]+=1;
header('Location: index.php');
}else{
$msg = "error";
header('Location: checkout.php');
}
}
}
//the plus button
if(isset($_GET['plus'])){
$_SESSION['product_'.$_GET['plus']]+=1;
if($_SESSION['product_'.$_GET['plus']] < 1){
header('Location: checkout.php');
}else{
header('Location: checkout.php');
}}
//the minus button
if(isset($_GET['remove'])){
$_SESSION['product_'.$_GET['remove']]--;
if($_SESSION['product_'.$_GET['remove']] < 1){
header('Location: checkout.php');
}else{
header('Location: checkout.php');
}
}
//the remove button
if(isset($_GET['delete'])){
$_SESSION['product_'.$_GET['delete']] = '0';
header('Location: checkout.php');
}
function cart(){
global $conn;
$fabric_options = '';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){
$fabric_options .= "<option value=''>{$rows['tecido']}</option>";
}
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
$btn_add='<a class="btn btn-success" href="cart.php?plus='.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
$btn_remove = '<a class="btn btn-warning" href="cart.php?remove='.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
$btn_delete='<a class="btn btn-default delete_btn" href="cart.php?delete='.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';
if($rows['variante'] < 1){
$vari="";
}else{
$vari = "-".$rows['variante'];
}
$product = '
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
<td style="width:15%;">
<select id="fabric" class="form-control selectpicker" required="" >
'. $fabric_options . '
</select>
</td>
<td>
<select id="size" class="form-control selectpicker" required style="width:80%;" >
<option value="50">50x50</option>
<option value="45">45x45</option>
</select>
</td>
<td>'.$value.'</td>
<td>R$</td>
<td>sub.total</td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
}
}
}
}
}
My LocalStorage script in checkout.php
<script >
$(function() {
if (localStorage.getItem('fabric')) {
$("#fabric option").eq(localStorage.getItem('fabric')).prop('selected', true);
}
$("#fabric").on('change', function() {
localStorage.setItem('fabric', $('option:selected', this).index());
});
});
</script>
<script >
$(function() {
if (localStorage.getItem('size')) {
$("#size option").eq(localStorage.getItem('size')).prop('selected', true);
}
$("#size").on('change', function() {
localStorage.setItem('size', $('option:selected', this).index());
});
});
</script>

Related

Message show when all dropdown items have inserted

I have a problem. I want when inserted a dropdown item, then this item not able to show in a drop-down in next time. It's working well. Now I want when every dropdown item has inserted, then need to show this message 'All users have assigned'. I am trying but its my code is not working. How can I do that?
Thanks!
<?php
$user_info2 = $wpdb->get_results( "SELECT * FROM user_contact_info WHERE user_company = $company_id" );
if (empty($user_info2))
{
echo "<h2>All users have assigned</h2>";
}
else
{
?>
<select type="text" name="ap_user" id="county" style="font-family: 'FontAwesome', Arial;" class="form-control" required >
<option disabled selected value> &#xf00c Select User</option>
<?php
foreach ($user_info2 as $user)
{
$assigns = $wpdb->get_results( "SELECT * from user_searches WHERE ap_user = $user->id AND ap_company = $company_id AND ap_project = $id " );
// foreach ($assigns as $assigned)
// {
if(!$assigns)
{
echo '<option value="'.$user->id.'" >'.$user->user_name.'</option>';
}
// }
}
?>
</select>
<?php
}
?>

Delete li entry in database with PHP

I am working on a website where the user can enter the money he owes a friend. On one page the user can see all the entrys he made so far and should be able to delete them aswell. All entrys are inserted in a DB. For this overview page I use following structure:
<ul class="list-group">
<?php
$isEmpty = true;
while ($data = mysql_fetch_array($res)) {
if ($data['isDebt'] == 0) {
$isEmpty = false; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<li class="list-group-item" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>"><span class="badge"><?php echo $data['value']; ?></span><?php echo $data['name']; ?>
<button name="delete" type="submit" id="delete" class="btn btn-xs btn-danger pull-right">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</li>
</form>
<?php }
}
if ($isEmpty) { ?>
<li class="list-group-item">No debt!</li>
<?php
} ?>
</ul>
One debt entry has the following values:
Debt_ID (numeric)
Name (like "pizza from jack")
Value (the price. for example "10")
The button for each li element should delete the entry in the DB via Debt_ID. I've used the following SQL statement so far:
DELETE FROM Debt WHERE Debt_ID='$debt_ID';
In PHP it looked like this:
if (isset($_GET['delete'])) {
$debt_ID = trim($_POST['Debt_ID']);
$res = mysql_query("DELETE FROM Debt WHERE Debt_ID='$debt_ID';");
if ($res) {
$errTyp = "success";
$errMSG = "Successfully deleted";
} else {
$errTyp = "danger";
$errMSG = "Error occured";
}
}
My problem right now is that I am not able to get the Debt_ID which I've entered with PHP in the li element. Does anyone know a better approach or what I am doing wrong?
I am developping with Cloud9 so I could invite someone if interested.
When you load all the debts, you can do that with a select statement and loop through the result set. In the loop you can put the id in hidden inputs in each li element:
$sql = "SELECT debt_id, name, value FROM debts WHERE user_id = " . $user_id;
$result = $conn -> query($sql);
if ($result -> num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>
<span>' . $row["name"] . '</span>
<span>' . $row["value"] . '</span>
<input type="hidden" value="' . $row['debt_id'] . ' name="id-to-delete">
</li>';
}
} else {
echo "no results";
}
The delete.php file should contain:
<?php
if (isset($_POST['id-to-delete'])) {
$idToDelete = $_POST['id-to-delete'];
// sql to delete a record
$sql = 'DELETE FROM debts WHERE debt_id=' . $idToDelete;
if ($conn->query($sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
After the form element simply add
<input type="hidden" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>">
Then remove the same information from the li element.
When submitting a form, input elements with a name attribute are what gets passed along to the next page.

Dropdown in loop only gets the first item value from foreach loop php/ajax

I got two dropdowns for my product in my cart.
All products are stored in sessions inside of a foreach loop.
But my dropdowns only work for the first product from loop.
Exemple: if i have 2 products in my cart the fisrt product row gets the cost based on both dorpdowns.
but the second product is getting the same cost from the first dropdown.
can someone please tell me how to fix this.
my script in checkout.php
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
var cost = $(this).attr('data-id');
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:cost,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + cost).text(data.val);
});
}
}
});
My php foreach loop in cart.php
function cart(){
global $conn;
$fabric_options = '<option>Select Fabric</option>';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){
$tecido=$rows['tecido'];
$id_price=$rows['id_price'];
$t50='50';
$t45='45';
$fabric_options .= '<option value="'.$id_price.'">'.$tecido.'</option>';
}
if(!isset($_SESSION['icms'])) {
$_SESSION['icms']='0';
}else{
$_SESSION['icms'];
}
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
$btn_add ='<button type="button" class="btn btn-success actions plus" data-action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></button>';
$btn_remove ='<button type="button" class="btn btn-warning actions less" data-action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></button>';
$btn_delete ='<button type="button" class="btn btn-default actions" data-action="delete" product_id="'.$id.'" onclick="deleteRow(this)"><i class="fa fa-times fa-lg" aria-hidden="true"></i></button>';
if($rows['variante'] < 1){
$vari="";
}else{
$vari = "-".$rows['variante'];
}
$product = '
<tr>
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
<td style="width:15%;">
<select name="fabric" class="fabric select form-control selectpicker" required="" data-id="'.$id.'">
'. $fabric_options . '
</select>
</td>
<td>
<select data-id="'.$id.'" class="select size form-control selectpicker" required style="width:80%;" >
<option>Select size</option>
<option value="'.$t50.'">50x'.$t50.'</option>
<option value="'.$t45.'">45x'.$t45.'</option>
</select>
</td>
<td class="product'.$id.'">'.$value.'</td>
<td class="icms">R$: '.$_SESSION['icms'].'</td>
<td class="total'.$id.'" data-id="'.$id.'">R$: '.$value * $_SESSION['icms'] .' </td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
}
}
}
}
}
and this is where my calculations are made..
calculates.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php'; //session allways start here
if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$prod = $_GET['prod_id'];
$prodname = 'product_'.$prod;
$query3 =" SELECT * FROM valores_almofadas WHERE size='$size_id' AND price_id ='$fabric_id'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
}
echo json_encode( $_SESSION['icms']);
}
how can i make my dropdown work foreach product?
The problem is that var fabricID = $(".fabric").val() is selecting the value from the first element it finds with the fabric class. This will be the same element (the first one) every time, no matter how many elements exist on the page with that class.
You need to select the value from the correct elements. This is made slightly trickier by the fact that you need to send both the fabric and size values simultaneously. Luckily you have got the row ID as a data attribute on both the <select> elements, so we can use this to match them up.
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
//use the data-id attribute of the selected element to match the correct elements
var id = $(this).data("id");
var fabricID = $('.fabric[data-id=' + id + ']').val();
var sizeID = $('.size[data-id=' + id + ']').val();
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:id,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + id).text(data.val);
});
}
}
});

Change price variable based on a dropdown selection with php and jquery

Problem: How can i get the selected price from a dropdown menu and use it instead of the original price of the current product stored in the database?
My approach: I've been able to update a label with the selected price, but I still need to override the current price of the product. I'm pretty clueless right now.
Additional information: The current price saved in the database is $price which need to be overridden by either $prijshalf or $prijsheel that are both also stored in the database.
The JQuery Code for updating the label:
<script type="text/javascript">
$(document).ready(function() {
$('.dropdown').change(function() {
var price = 0;
$('.dropdown').each(function() {
if($(this).val() != 0) {
price = parseFloat($(this).val());
}
});
$('#costLabel').text('€ ' + price.toFixed(2));
});
});
</script>
This code block gets the value of the selected dropdown menu item and puts it in the label #costLabel
The PHP Code for rendering the products:
$product_list = "";
while($row = mysql_fetch_array($results)){
$id = $row["id"];
$product_name = substr($row["product_name"],0,25);
$price = $row["price"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$beschrijving = substr($row["details"],0,25);
$afbeelding = '<img src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="50" height="50" />';
$dropdown = $row["dropdown"];
$dropdown2 = $row["dropdown2"];
$prijshalf = $row["prijshalf"];
$prijsheel = $row["prijsheel"];
if($dropdown != "" || $dropdown2 != ""){
$dropdownshow = "<select name='dropdown' id='dropdown' class='dropdown'>
<option name='prijshalf' value='$prijshalf'>$dropdown</option>
<option name='prijsheel' value='$prijsheel'>$dropdown2</option>
</select>";
}
else{
$dropdownshow = "";
}
$product_list .= "<div class='produkt'>
<div class='hardlopers'>
$afbeelding
<div class='subinfo'>
<span class='prijs-info'>Prijs:</span><span class='prijs'><label id='costLabel' name='costLabel'>$price</label> </span>
<span class='productnaam'>$product_name</span>
<span class='dropdown'>
$dropdownshow
</span>
<form id='form1' name='form1' method='post' action='homepage.php#redirect'>
<input type='hidden' name='pid' id='pid' value='$id' />
<input type='submit' name='button' id='button' value='' />
</form>
<span class='info'></span>
</div>
</div>
</div>
";
}
// Prints out the products to screen
echo $product_list;
I can't see how is your process of adding an item to the cart, so i can't tell you how. But you can try to move the dropdown into the <form> tag, later with php you get the value and if it is prijshalf or prijsheel do the math. The same with js, put the selected value of the dropdown in a hidden input within the <form> if you doesn't want the dropdown into the <form>, but i don't see why it shouldn't, send it to the server and do the math there. All is up to you.
Always use js just to show the info, always do the calculation and validation with php in the server for security reasons.
Happy coding

Can't get the value from other textfield except the first one

I use the code from phpwebcommerce's shopping cart tutorial, and I am trying to add a text field for user to insert quantity. Since there are different number of choices for a single product, so I use the while statement to query the sub-items and put a text field plus a add button beside each of them. But it only takes the quantity for the first item, and not the rest. If I insert a quantity for the first item, and click on "add" on any of other items, it will still store the first in my cart, which it should not... I am stuck... can someone help me out?
<?php
function displayprodDetail($pdId)
{
$query = mysql_query("SELECT * FROM product_image WHERE p_id ='$pdId'");
WHILE($datarows = mysql_fetch_array($query))
{
$p_num = $datarows['p_number'];
echo '<h1><span>'.$p_num.' -- $'.$datarows['price'].'</span></h1>';
echo '<div id="prodPic"><img src ="'.$datarows['image'].'"/><br /></div>';
echo '<div id="items">';
$sql = mysql_query("SELECT * FROM items WHERE item_number LIKE '$p_num/%' ORDER BY item_number ASC");
$numProduct = dbNumRows($sql);
if($numProduct > 1)
{
echo '<table border="0" cellspacing="0">';
WHILE($data = mysql_fetch_array($sql))
{
$itemId = $data['item_id'];
$p_num = $data['item_number'];
echo '<tr>';
echo '<td><INPUT TYPE="HIDDEN" NAME="'.$itemId.'" VALUE="'.$itemId.'">'.$p_num.'</td>';
echo '<td> Qty: <input type="number" name="qty" id="qty" style="width:30px"></td>';
$cart_url = "cart.php?action=add&i=$itemId&qty=";
?>
<td><input type="Submit" name="Submit" value="Add" onClick="window.location.href='<?php echo $cart_url; ?>' +document.getElementById('qty').value;" ></td>
<?php
echo '</tr>';
}
echo '</table>';
}
else
{
echo 'Items are currently not available.<br>Contact us for more detail.';
}
echo '</div>';
}
}
?>
Here is the add to cart function:
function addToCart()
{
// make sure the product id exist
if (isset($_GET['i']) && (int)$_GET['i'] > 0)
{
$itemId = (int)$_GET['i'];
}
else
{
header('Location: home.php');
}
if (isset($_GET['qty']) && (int)$_GET['qty'] > 0)
{
$qty = (int)$_GET['qty'];
}
// current session id
$sid = session_id();
// check if the product is already
// in cart table for this session
$sql = mysql_query("SELECT item_id FROM cart_table WHERE item_id = $itemId AND ct_session_id = '$sid'");
if (dbNumRows($sql) == 0)
{
// put the product in cart table
$sql = mysql_query("INSERT INTO cart_table (item_id, ct_qty, ct_session_id, ct_date) VALUES ($itemId, $qty, '$sid', now())");
}
else
{
// update product quantity in cart table
$sql = mysql_query("UPDATE cart_table SET ct_qty = ct_qty + $qty WHERE ct_session_id = '$sid' AND item_id = $itemId");
}
// an extra job for us here is to remove abandoned carts.
// right now the best option is to call this function here
deleteAbandonedCart();
header('Location: ' . $_SESSION['shop_return_url']);
}
since you are naming your input boxes same, that's why its not working as expected, try something like:
<input type="number" name="qty_<?php echo $itemId; ?>" id="qty_<?php echo $itemId; ?>" style="width:30px">...
...
<td><input type="Submit" name="Submit" value="Add" onClick="window.location.href='<?php echo $cart_url; ?>' +document.getElementById('qty_<?php echo $itemId; ?>').value;" ></td>

Categories