I'm trying to add product into add cart. Please tell me what is the best way.
My mess code is.
if(isset($_SESSION['id'])) {
echo "IF part";
$_SESSION['id'] = $_SESSION['id'] + $_SESSION['id'];
$k = $_SESSION['id'];
// store session data
$_SESSION[$k]['product_name']=$_REQUEST['product_name_value'];
$_SESSION[$k]['product_price']=$_REQUEST['product_price_value'];
$_SESSION[$k]['shop_name']=$_REQUEST['shop_name_value'];
$_SESSION[$k]['Quantity']=$_REQUEST['selquantity'];
$_SESSION[$k]['color']=$_REQUEST['txtcolor'];
$_SESSION[$k]['Size']=$_REQUEST['selsize'];
$_SESSION[$k]['Product_Type']=$_REQUEST['selproducttype'];
$_SESSION[$k]['Remarks']=$_REQUEST['Remarks'];
$_SESSION[$k]['final_price']=$_REQUEST['final_price_value'];
$_SESSION[$k]['txturl']=$_REQUEST['txturl'];
}else {
echo "else part";
$_SESSION['id'] = 1;
// store session data
$_SESSION[$k]['product_name']=$_REQUEST['product_name_value'];
$_SESSION[$k]['product_price']=$_REQUEST['product_price_value'];
$_SESSION[$k]['shop_name']=$_REQUEST['shop_name_value'];
$_SESSION[$k]['Quantity']=$_REQUEST['selquantity'];
$_SESSION[$k]['color']=$_REQUEST['txtcolor'];
$_SESSION[$k]['Size']=$_REQUEST['selsize'];
$_SESSION[$k]['Product_Type']=$_REQUEST['selproducttype'];
$_SESSION[$k]['Remarks']=$_REQUEST['Remarks'];
$_SESSION[$k]['final_price']=$_REQUEST['final_price_value'];
$_SESSION[$k]['txturl']=$_REQUEST['txturl'];
}
I'm trying to add these product details into array.
thanks
Don't repeat yourself ;) means if you have two lines of code that are identical check if you really need to write it twice!
if(!isset($_SESSION['cart'])) {
// create cart
$_SESSION['cart'] = array();
}
// create item
$item = array();
// fill item
$item['product_name']=$_REQUEST['product_name_value'];
$item['product_price']=$_REQUEST['product_price_value'];
$item['shop_name']=$_REQUEST['shop_name_value'];
$item['Quantity']=$_REQUEST['selquantity'];
$item['color']=$_REQUEST['txtcolor'];
$item['Size']=$_REQUEST['selsize'];
$item['Product_Type']=$_REQUEST['selproducttype'];
$item['Remarks']=$_REQUEST['Remarks'];
$item['final_price']=$_REQUEST['final_price_value'];
$item['txturl']=$_REQUEST['txturl'];
// add item to cart
$_SESSION['cart'][] = $item;
You should first do some factorization on your code with creating a function to add the data to the $_SESSION.
Then, it's impossible to give you an answer, there's no "best way", there's only a way that suits your need and you're the only one which can find it.
See below.
$sql = "INSERT INTO ordertb (time, cust_id, prod_id, quantity, pmt_mode, city, delivery_state,amtval) VALUES ( '".date("Y-m-d H:i:s")."','".$idval1."','".$item["product_code"]."','".$item["qty"]."','".$_SESSION['spmt1']."','".$_SESSION['scity']."','1','".$item["subtotal"]."')";
Related
I have a Table where user can create row with adding input fields dynamically (combination with jquery). I'm successfully able to insert it into the mysql database.
If users want to edit the added already existing fields, I have an edit page where the values are fetched from the mysql DB and populated again into the dynamically creatable table.
Now there are the below probabilities:-
User only makes minor changes on the existing values. In that case
the table has to be UPDATED with the changed values
User Deletes one/multiple row(randomly selected and as per users wish). So when form submitted the php query should only DELETE that perticular row/s in the DB.
User ADDS another row to the previous existing row values, in that case the php query should UPDATE the previous values and INSERT the newly added row values.
The above sequence is not necessarilly restricted the same order. User can perform all the above three function simultaneously at the same time.
Now my problem is(only for the backend) I'm finding a hard time to frame a php & sql query so as to update to the mysql.
my php
if(isset($_POST['submit'])){
$number1 = count($_POST['item']); //
for($i=0; $i<$number1; $i++){
$item = strip_tags(trim($_POST['item'][$i]));
$description = strip_tags(trim($_POST['description'][$i]));
$unitcost = strip_tags(trim($_POST['unitcost'][$i]));
$qty = strip_tags(trim($_POST['qty'][$i])); // Quantity
$sno = strip_tags(trim($_POST['sno'][$i]));// serial number
//QUERY1 if minor updates to above variable then UPDATE (eg, qty value is changed from 3 to 4)
//QUERY2 if row is deleted then DELETE that particular row from db (eg, sno 3 deleted from the table should DELETE corresponding mysql DB values also)
//QUERY3 if row is added then that particular row values should be INSERT (eg, sno 4 is added which is not in the mysql db. So this has to be INSERTED.)
}
}
Pardon me to have asked such question. I'm wasting a whole lot of time with the above queries unable to execute properly. I only require an idea not necessarily the whole code.
Hope all of you out there would advice me some ideas on how this could be implemented. Thanks for the help in advance. Expecting a positive reply.
NB: Just to remind you again, The front end is a Dynamically ADD/DELETE Input Field table
This sounds like a frontend problem. You need to define how you tell the backend whats happening.
<input name="items[$i][name]" />
This will show up as nice array to loop through in php.
foreach($_POST[items] AS $item){
if( $item['delete'] ){
//delete code
}
}else{
//Insert/Update
}
If you want to delete something simply make the field hidden and add a flag to it.
<input type="hidden" name="items[$i][delete]" value="1" />
<input type="hidden" name="items[$i][id]" />
Thank for the reply, appreciate #ckrudelux and #codefather for their intention to help me.
Although their advise didn't help me to structure my query. So I had a long workaround and found out below solution. I'm posting the solution because I couldn't find any article online when it comes to UPDATE/DELETE a dynamically generated input table.
Hope this would be of help to someone.
So what I did basically is that I took all the values into array.
In my dynamically generated add input table code, I added an <input type="hidden" name="sno[]" value="newrow">. So this will be clubbed with the form post. I'm using the normal html post and not ajax.
now my submit.php has ben changed to below
if(isset($_POST['submit'])){
$productid = $_POST['productd'];// No striptag functions
// due to illustration purpose
// First of all, we need to fetch the querying db table.
// This is required in order to compare the existing row values
// with the posted values
$fetchproduct = $link->prepare("SELECT * FROM product WHERE productid=?");
$fetchproduct ->bind_param('s',$productid);
$fetchproduct ->execute();
$fetchresult = $fetchproduct ->get_result();
$serialnumber=array(); // Assigning array to fetch the primary key: Serial Number
while($row = $fetchresult->fetch_assoc()){
$serialnumber[] = $row["sno"];
}
//Newly Inserted Values
//$_POST['sno'] is taken from the dynamic input field defined earlier in this post.
//Basically what we are doing here is we are comparing (the values
//which have been posted from the primary page) and (values present in the db table).
//The difference will give an array of newly inserted table input field values
$insert = array_diff($_POST['sno'],$serialnumber);
//Deleted Values
// This will Difference those values in the db table and values which are
// deleted from the primary dynamic table page
$delete = array_diff($serialnumber,$_POST['sno']);
$countdelete = count($delete); // Counting how many values have been
// lined up for deleting
//Updated Values
// array_intersect will give us the common values present in both the array.
// This means that there is no deletion or insertion to the dynamic table fields.
$intersect = array_intersect($serialnumber, $_POST['sno']);
$update = array_values($intersect);
$countupdate = count($update);
//INSERT ADDED VALUES TO DB
foreach($insert as $key=>$ivalue){
// ID
if(isset($_POST['id'][$key]) && !empty($_POST['id'][$key])) {
$id = strip_tags(trim($_POST['id'][$key]));
}
// ITEM
if(isset($_POST['item'][$key]) && !empty($_POST['item'][$key])) {
$item = strip_tags(trim($_POST['item'][$key]));
}
// DESCRIPTION
if(isset($_POST['description'][$key]) && !empty($_POST['description'][$key])) {
$description = strip_tags(trim($_POST['description'][$key]));
}
// UNITCOST
if(isset($_POST['unitcost'][$key]) && !empty($_POST['unitcost'][$key])) {
$unitcost = strip_tags(trim($_POST['unitcost'][$key]));
}
// QUANTITY
if(isset($_POST['qty'][$key]) && !empty($_POST['qty'][$key])) {
$qty = strip_tags(trim($_POST['qty'][$key]));
}
// AMOUNT
if(isset($_POST['amount'][$key]) && !empty($_POST['amount'][$key])) {
$amount = strip_tags(trim($_POST['amount'][$key]));
}
// INSERT INTO THE DATABASE
$inserttable = $link->prepare("INSERT INTO product (productid, item, description, unitcost, qty, amount) VALUES(?,?,?,?,?,?)");
$inserttable->bind_param('ssssss', $id, $item, $description, $unitcost, $qty, $amount);
$inserttable->execute();
if($inserttable){
header( 'Location:to/your/redirect page.php' ) ; // NOT MANDADTORY, You can put whatever you want
$_SESSION['updatemsg'] = "Success";
}
}
//UPDATE EXISTING VALUES TO DB
for($j=0; $j<$countupdate; $j++){
// ID
if(isset($_POST['id'][$j]) && !empty($_POST['id'][$j])) {
$uid = strip_tags(trim($_POST['id'][$j]));
}
// ITEM
if(isset($_POST['item'][$j]) && !empty($_POST['item'][$j])) {
$uitem = strip_tags(trim($_POST['item'][$j]));
}
// DESCRIPTION
if(isset($_POST['description'][$j]) && !empty($_POST['description'][$j])) {
$udescription = strip_tags(trim($_POST['description'][$j]));
}
// UNITCOST
if(isset($_POST['unitcost'][$j]) && !empty($_POST['unitcost'][$j])) {
$uunitcost = strip_tags(trim($_POST['unitcost'][$j]));
}
// QUANTITY
if(isset($_POST['qty'][$j]) && !empty($_POST['qty'][$j])) {
$uqty = strip_tags(trim($_POST['qty'][$j]));
}
// AMOUNT
if(isset($_POST['amount'][$j]) && !empty($_POST['amount'][$j])) {
$uamount = strip_tags(trim($_POST['amount'][$j]));
}
// UPDATE THE DATABASE
$updatetable = $link->prepare("UPDATE product SET item=?, description=?, unitcost=?, qty=?, amount=? WHERE sno=?");
$updatetable->bind_param('ssssss', $uitem, $udescription, $uunitcost, $uqty, $uamount, $update[$j]);
$updatetable->execute();
if($updatetable){
$_SESSION['updatemsg'] = "Success";
}
}
//DELETE VALUES FROM DB
foreach($delete as $sno){
$deletetable = $link->prepare("DELETE FROM product WHERE sno=?");
$deletetable->bind_param('s', $sno);
$deletetable->execute();
if($deletetable){
$_SESSION['updatemsg'] = "Success";
}
}
}else {
$_SESSION['updatemsg'] = "Error";
}
}
I am creating a shopping cart with an array in php. The array first array is to store the ShoeId and the quantity which was POST from the previous page. It is stored in the $_SESSION['cart'].
I then compared the cart with a new array called $cleanArray to find duplicates and replace it by increasing the quantity. However I came into an issue that I don't understand and after spending countless of hours I decided to ask here.
//creating a final cart
$cleanArray = array();
//to prevent sql injection
$shoeID = $conn->real_escape_string($_POST['shoeID']);
$quantity = $conn->real_escape_string($_POST['quantity']);
// $_SESSION['cart'] = array();
If I leave the $_SESSION['cart'] = array(); in the code the cart will keep clearing itself.
However, If i add it, refresh my webpage and then remove that code again. My shopping cart would work as intended.
//checking if Cart Array exist and if ShoeID and quantity has been selected
if (isset($_POST['shoeID']) && ($_POST['quantity'])){
if(isset($_SESSION['cart'])){
echo "shoeID: $shoeID";
echo "<br>";
echo "Quantity: $quantity";
echo "<br>";
$_SESSION['cart'][] = array('shoeId' => $shoeID, 'quantity' => $quantity);
$cartArray = $_SESSION['cart'];
//find for duplicate shoeId and then increase the quantity.
foreach($cartArray as $item){
if(isset($cleanArray[$item['shoeId']])){
$cleanArray[$item['shoeId']]['quantity'] += $item['quantity'];
} else {
$cleanArray[$item['shoeId']] = $item;
}
}
} else {
echo "Cart Is Empty!";
}
$cleanArray = array_values($cleanArray);
print_r($cleanArray);
$_SESSION['finalCart'] = $cleanArray;
Any forms of suggestion would be helpful as I am new to php and I am trying to understand more about it. thank you!
I am trying to allow users to add destinations to their favourites page, similar to adding products to a shopping cart. I am doing this by saving the destinations to a session array and then adding this session array onto the end of an SQL SELECT statment to print the destinations. Although the code I have written only allows me to add one destination to favourites. Can anyone point my in the right direction.
if(empty($_SESSION['cart'])){
$_SESSION['cart'] = array();
} else {
array_push($_SESSION['cart'], $_GET['theid']);
// HOW TO LOOP THROUGH SESSION CART
$str = implode(',', $_SESSION['cart']) ;
$query = "SELECT * FROM Destinations WHERE DestID IN ($str)" ;
$result = mysqli_query($connection, $query);
while($row=mysqli_fetch_assoc($result)){
echo $row['DestName'].' '.$row['DestRating'].
' <img src="Images/'.$row['DestImage'].'" /> <br/>';
}
}
I want to create stock management system in my website using php. It sounds like 'balancing' stock in database with amount of items that will purchased. If the item's amount is more than the item's stock, the website should displaying an alert. So, the amount of item cannot be more than the item's stock in database.
Here's my code :
$stock = array();
foreach ($_SESSION['cart'] as $k => $v) {
$sql = mysql_query("SELECT book_stock FROM book WHERE book_title='$k'");
while ($row = mysql_fetch_assoc($sql)) {
$stock[] = $row['book_stock'];
}
if ($stock < $v) {
echo "Stock less than the amount";
}
else {
echo "Stock sufficient";
}
}
The $k variable store the item's name in the session cart. And the $v variable store the item's amount in the transaction.
The item's amount will be increased if the visitor click 'Increase' button.
But if i increase the item's amount, the if and else logic like "isn't working". No matter how much the item's amount is added, the if and else logic keep print "Stock Sufficient".
Can anyone help me to solve this? Thanks in advance :)
Edit :
The variable in original code is in indonesian. So when i'm typing this post, i'm editing the variables too here. So if the variables is different, i'm just forget to rename it. So i edit the script again :)
$sql = mysql_query("SELECT book_stock FROM ooku WHERE book_title='$k'");
I am assuming that your query will return unique book (single book) stock detail, you have to use $stok instead of $stok[] Array
while ($row = mysql_fetch_assoc($sql)) {
$stok = $row['book_stock'];
}
I am trying to pass data from a product page into a shopping cart page using an array. There are multiple attributes that the viewcart.php will receive from the previous page (price, link, title, and retailer). I’d like to save them all using an array. For each additional item a customer adds to the shopping cart, I’m trying to get a counter variable ($i) to increment an array $_SESSION[‘cart’][$i][‘attribute’]. How do I do this?
I’m not sure this is the right way to add new products to the cart. In the end, I’d like a way to be able to display all the products in the cart using a for loop. This is the start I have so far on the shopping cart script:
<?php
// The shopping cart needs sessions, so start one
session_start();
#$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];
if($link) {
//new item selected
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
$_SESSION['items'] = 0;
$_SESSION['total_price'] ='0.00';
}
if(isset($_SESSION['cart'][$link])) {
$_SESSION['cart'][$link]++;
} else {
$_SESSION['cart'][$link] = 1;
}
}
if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
echo " in your cart and we're working to display them";
}
else {
echo "<p>There are no items in your cart</p><hr/>";
}
?>
This is the for loop that I’m thinking I could use. I’m looking for some way to display all the items in the array.
for ($x=0; $x<=$i; $i++)
{
echo "The price is " . $_SESSION['cart'][$x][price] . " Retailer is " . $_SESSION['cart'][$x] [retailer] . "<br>";
}
The easiest way to do this is by creating a temp_cart table in your database.. in which you should store the items that user adds to their cart.. Then on checkout page.. you can simply display them using select query. In that way.. it will be easier for you to allow the user to edit their cart on viewcart.php page.
You could:
Have another session variable with the counter and increment it each add?
Or
$i= Count($_SESSION['cart'])+1;
Or
Don't specify an index at all:
$tmp["cart"]["retailer"] = "123";
Etc etc..
$_SESSION['cart'][] = $tmp["cart"];
I would be storing the products into a database if I was you..
I don't like the way you are doing this. Session management is very simple for shopping carts. Keep your session as lite as possible. Storing price in the session is very bad way, as it can be easily manipulated.
Here is a simple example of what you can use.
if(isset($_SESSION['items'][$_GET['item_id']])) {
$_SESSION['items'][$_GET['item_id']]++; //add one to the total count
} else {
$_SESSION['items'][$_GET['item_id']] = 1; //If added for the first time
}
Now process it
foreach($_SESSION['items'] as $id => $count) {
echo $id; // product id
echo $count; // product count
}
P.S: Remember to sanitize the input. I have omitted that