PHP Session Variables - passing through pages - php

Im hoping someone can point me in the right direction of where im going wrong as I feel like im going around in circles!
Im putting together a simple shopping applications - its only very basic at the moment to demonstrate techniques.
The scenario is that there is one database table with items in. They have been split into a blue and red range of items.
On the index page the user has the option of going to either the blue or red items.
Once on the red (or blue) items page, items are displayed and current price and stock level is pulled from the database (MySQL). The user then selects one item and clicks the buy button to add it into their cart.
The page then redirects to the shopping cart page where the user can either update the quantity of the item, proceed to the checkout page or return to the 'red' or 'blue' ranges.
My issue is this.....
1) How do I set up my session array to capture the items as they are added on the buy 'click'?
So far I have this on the top of all pages...
<?php session_start();
?>
However only one item seems to be able to be added to the 'cart'.
This is how im pulling items from my DB:
<?php
$result = mysql_query ('SELECT * FROM items WHERE colour="red"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
}
?></p>
2) This is the code for the form action under each item on either the red or blue page.
<form method="post" action="cart.php">
<p>
<input type="submit" name="submit" value="Buy" />
<input type="hidden" name="cart" value="add" />
<input type="hidden" name="item" value="redplate" />
</p>
</form>
3) How do I display the 'ordered' item in the checkout page after any quantity updates on the shopping cart page?
So far this is what it on the shopping cart page - would I repeat this on the checkout page pulling with it the updated quantity??....
<?php
$submit = $_POST["submit"];
//Call the function and save all data into the array $_SESSION['form']
if($submit == "Buy"){setSessionVars();}
function setSessionVars() {
$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
$item[$fieldname] = $fieldvalue;
}
$_SESSION['cart'] = $item;
echo " <table>
<tr>
<td>
<img src=\"images/{$item['item']}.jpg\" />
<td/>
<td>
{$item['item']} =
</td>
<td>
<input type=\"text(5)\" name=\"value\" value=\"1\" />
<input type=\"submit\" name=\"puchasedquan\" value=\"Click to update\" />
</td>
</tr>
</table>";
}
?>
Any help would be greatly appreciated!! I feel as if i'm traveling around in circles!

The problem with storing things in the PHP session vars is that they are stored in cookies, that means they require cookies to be turned on. Okay, most browsers have cookies set nowadays.
But how about if you read values directly from a client file, and put that into your database? Whats to stop someone from hacking the cookie file where it says "subtotal=10000" and changing the value to "subtotal=1", then push that through your system?
Your system would be more robust if you actually store the shopping session in your database, e.g.
CREATE TABLE tbl_shopping_session(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
php_session_key VARCHAR(32),
coupon_id INT,
FOREIGN KEY(coupon_id) REFERENCES tbl_coupons(id),
updated TIMESTAMP /* a timestamp is added to find & del old sessions */
) ENGINE = InnoDB;
CREATE TABLE tbl_shopping_cart(
shopping_session_id INT,
FOREIGN KEY(shopping_session_id) REFERENCES tbl_shopping_session(id) ON DELETE CASCADE,
product_id INT,
FOREIGN KEY(product_id) REFERENCES tbl_products(id),
cart_qty INT /* or DECIMAL(9,3) or something */,
subtotal DECIMAL(18,4)
) ENGINE = InnoDB;
From there on you could get the picture... the php_session_key is used to identify the current shopping session, and the current session id is used to find & store the cart items in a separate table.

The big mistake here is, you are putting all you datas on one session variable altogether, i.e. $_SESSION['cart'].
Since you want to insert multiple item on the sessions, you have use $_SESSION['cart'][] to insert the items.
Whenever you are trying to get the values stored, again use a for loop to read as well as .
foreach($_SESSION['cart'] as $cartItem) {
$cartItem; // will have all the item individually on each pass
}

try this
$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
$item[$fieldname][] = $fieldvalue;
}

The $_SESSION keys are being replaced when you add more, so really it's just overwriting an existing value, you could add this:
foreach($_POST as $fieldname => $fieldvalue) {
// Now the array will be enumerated
$item[$fieldname][] = $fieldvalue;
}
print_r($item);

Related

update cart with php sessions

I am trying to update my cart quantity,my products are displayed with foreach loop .So, I tried to update it through this code , it worked but only for the first item selected on addtocart submit . What is the problem ? how to make the update for each item on one update button click ?
if (isset($_POST["quansub"]) ){
$itq = $_POST["itq"];
$_SESSION["itq"] = $itq;
$_SESSION["incart"][$select]["item_quantity"]= $_SESSION["itq"];
header("location:selecteditems.php");
}
Is this the sort of thing you want?
I would suggest for each item in your cart have something like this:
<input type='hidden' name='quantity[1]' id='quantity[1]'>
<input type='hidden' name='quantity[2]' id='quantity[2]'>
foreach($_POST['item'] AS $key=>$value){
$qty = $_POST["quantity"][$key];
$_SESSION["quantity"][$key] = $qty;
$_SESSION["incart"][$select]["item_quantity"]= $_SESSION["quantity"][$key];
}
Where you have "$select", use it to do the following:
<input type="text" name="itq[<?= $select ?>]" value="<?php echo $val["item_quantity"]; ?>"/>
Then do the following in PHP:
if (isset($_POST["quansub"] && $_POST['itq'][$select])){
$_SESSION["incart"][$select]["item_quantity"] = $_POST["itq"][$select];
}
Move this code outside of the foreach loop:
if (isset($_POST["quansub"])){
header("location:selecteditems.php");
}
Having "quantity[1], quantity[2]" etc... makes it very easy to loop through the input values and get out their values. This is very useful when storing multiple items into a database that are using the same names.
Giving the names a unique "key" also means you can determine where they belong to in a database as well as you could give them the "key" by using their database or product id for example.
If you want me to explain individual parts to this let me know.

update quantity of input box specific to each id using session array

I am making a shopping cart using arrays and sessions.
I would like to update the quantity of an item that has a specific id number, without updating the other quantities which have different id number.
My code is bellow and to run it, you must get id from URL.
So just put ?id=1 in front of the .php in the address bar (as I am sure everyone is aware of more than me).
Cart.php
<?php
session_start();
// set the array and store in session
$_SESSION['items'][]=array(
'id'=>"'".$_GET['id']."'",
'qty'=> 1
);
// Display each array value stored in the session
foreach ($_SESSION['items'] as $value) {
// Display the id
echo 'The ID is ' ."''''" . $value['id'] ."''''" ;
// Display the Qty
echo 'the QTY ' ."''''" . $value['qty'] ."''''" ;
echo "<br/>";
//Echo a form that displays the Qty in a input box,
// My problem is that, I cant update the qty value in the input box where each id is different.
echo "<form method='post' action='id.php' name='edit'>
<p>Quantity: <input type=\"text\" size=\"20\" name='".$value['id']."' value='".$value['qty']."'/> </p><br>
<input class='save' name='update' value='update' type='submit'>
</form>";
}
// check if the update button is submited so that the qty value can be changed where the id number of the selected qty input box is edited
if (isset($_POST["update"])) {
$_SESSION['item'][$id]= $_POST["'".$value['id']."'"];
}
else
{
echo "quantity is updated";
}
?>
Unless you are making a $_SESSION['items'] Array of Arrays, change
$_SESSION['items'][]
to
$_SESSION['items']
Otherwise, you'll need a loop within your loop.
Right now, $value in
foreach ($_SESSION['items'] as $value) {
really represents an Array, which has your other Array in it. Additionally, you should not have more than one form with the same name. Don't put a form in a loop unless you're changing the name at each step of the loop.

String Encode, Array Decode

I'm new to PHP, I started about 3 weeks ago.
I have a string, which is used with $_POST to pass it to another page, the second page uses $_GET to get these url and split it as desired.
My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array.
So is there any encryption method or function I can use which is compatible with $_POST ( so I can send it to another page ) and decrypt it as an array ?
I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get.
tnx for your help.
You're thinking about this wrong. You NEVER trust information coming from the user's side.
For example, if your user sends a form that says what item they want, DO NOT include the price in the form. Instead, get the price from the server (database), where it can be trusted.
What you probably want to do is pass the contents of the users cart (i.e. the items he'd like to order) to the payment site.
Therefore, you should create a form like:
<form action="URL/to/paymentPage.php" method="post">
<!-- Item 1 -->
<input type="hidden" name="items[0]" value="productID1"/>
<input type="hidden" name="quantity[0]" value="quantity1"/>
<!-- Item 2 -->
<input type="hidden" name="items[1]" value="productID2"/>
<input type="hidden" name="quantity[1]" value="quantity2"/>
<!-- ... -->
<!-- Item n -->
<input type="hidden" name="items[n]" value="productIDn"/>
<input type="hidden" name="quantity[n]" value="quantityn"/>
<input type="submit" value="Order"/>
</form>
On the server in the file "URL/to/paymentPage.php" you can access the items using the following code:
<?php
$items = $_POST['items']; // Array of items ..
$quantities = $_POST['quantity']; // The array of quantities for each item ..
// Calculate the total price ..
$totalPrice = 0;
foreach($items as $idx => $itemID) {
if($quantities[$idx]>0) {
totalPrice += getPriceFromDB($itemID) * $quantities[$idx];
}
}
echo 'Total Price to pay: '.$totalPrice;
?>
where the function getPriceFromDB actually retrieves the price for the item/product with the id $itemID from your database or elsewhere... :)
However, the user items are usually stored in the session, and, therefore, there is no need to submit the again.. ;)
Despite not fully understanding what you're trying to achieve, you can use base64 encoding:
$encoded_string = base64_encode ($string);
$decoded_string = base64_decode ($encoded_string);

Help with a function php

I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);

PHP Mysql & Jquery dynamically populating multiple records

I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.

Categories