PHP SESSION HTML table carrying issue - php

I am adding items to my cart.php using an add in the URL.
case "add":
if (isset($_SESSION['cart'][$comic_id])) {
$_SESSION['cart'][$comic_id]++;
} else {
$_SESSION['cart'][$comic_id] = 1;}
... My items are presented into an HTML table in the cart.php. I just want to then re-call specific variables from the array in the checkout.php so the customer can confirm the order total along with their personal details.
I can only seem to carry the last added item/row over using SESSION variable when I use the following:
$_SESSION['totalnameqty']=$name . " " . $qty . " " . $cost;
...and then use an echo on the checkout.php page:
$totnamqty=$_SESSION['totnamqty'];
echo $totnamqty;
... I want to carry all items $name, $qty & $cost added to the HTML table in the cart.php to the checkout.php not just 1 item/row. Unsure of how to do this or if it is possible. Can somebody help?
Here is my cart.php:
if (isset($_SESSION['cart'][$comic_id])){
echo "<table border=\"0\" padding=\"10\" width=\"80%\">";
echo "<td colspan=\"1\" align=\"left\">Continue Shopping</div>";
echo "<td colspan=\"6\" align=\"right\">Empty Cart</td>";
echo "<tr height=\"20px\">";
echo "<tr height=\"20px\">";
echo "<td align=center>Image</td><td align=center>Title</td><td align=center>Description</td><td colspan=3 align=center>Copies (+/-)</td><td align=center>Price</td>";
echo "<tr height=\"20px\">";
foreach($_SESSION['cart'] as $comic_id => $qty) {
$sql = sprintf("SELECT title, description, cost, image_thumbnail
FROM comic
WHERE comic_id = %d;",$comic_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
list($name, $description, $price, $image_thumbnail) = mysql_fetch_row($result);
$cost = $price * $qty;
$total = $total + $cost;
$cost = number_format($cost,2);
$total = number_format($total,2);
$description = substr($description, 0, 250);
echo "<br><tr>";
echo "<td width=\"10px\" align=\"center\"><img height=100 align=center src=\"$image_thumbnail\">";
echo "<td align=\"center\">$name</td>";
echo "<td width=\"40%\" align=\"center\">$description...<a href=comic_dyn.php?comic_id=$comic_id>More Info</td>";
echo "<td width=\"30px\" align=\"center\">+<br><td align=\"center\">$qty <td width=\"20px\" align=\"center\">-</td>";
echo "<td align=\"right\">$$cost</td>";
echo "</tr>";
}
}
echo "<br><tr><tr height=100px>";
echo "<td><td><td colspan=\"4\" align=\"right\">Total:</td>";
echo "<td width=\"60px\" align=\"right\">$$total</td>";
echo "<tr><td colspan=\"7\" align=\"right\">Proceed to Checkout";
echo "<tr height=\"50px\">";
echo "</table>";
}else{
echo "Your cart is currently empty.";
echo "<br><br><td colspan=\"1\" align=\"left\">Continue Shopping</div>";
}
//session variables (to be carried to checkout.php
$_SESSION['cost']=$cost;
$_SESSION['name']=$name;
$_SESSION['qty']=$qty;
$_SESSION['totnamqty']=$name . " " . $qty . " " . $cost;

You're setting $name, $qty and $cost values inside a loop, therefore you are accessing the last set values below/outside of the loop. Also, you're using $comic_id at the beginning but below are using that same variable in your foreach statement. I'm guessing you can remove the foreach and instead use: $qty = $_SESSION['cart'][$comic_id]?
Otherwise, assuming the isset() at the top is incorrect, and that you are trying to loop each $comic_id from the cart; then you want to index your 'cost', 'name', 'qty' and 'tonamqty' values per $comic_id. eg. use something like this inside your foreach loop: $_SESSION['comics'][$comic_id]['cost'] = $cost;
However, I think a checkout approach without using session variables is more appropriate. I'd post what the user currently sees to checkout.php, rather than using the session data. Assume the session was accessed from multiple tabs and the user clicks checkout on an outdated tab. If using session variables, the server is only aware that the user requested to checkout the most recent items in the session, not what was actively visible.

Related

PHP passing values from generated textboxes

I'm creating a PHP web application in combination with SQL to order stuff. I'm randomly generating textboxes based on the amount of records I have. I want to pass the individual values to insert to the database. I want each cell to have a textbox in which I can input values and pass them with that cell. So if I want to order 2 of cell one I want to pass that value into a database.
Here's the code:
$i = 0;
if ($AanbodsTabel === false){
die(mysql_error());
}
while ($row = mysqli_fetch_array($AanbodsTabel)){
echo "<tr><td width = 4%>". htmlentities($row['Fustcode']) . "</td>";
echo "<td width = 8%>" . htmlentities($row['cultivar']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalPerFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelen']) . "</td>";
echo "<td width = 4%><input type ='text' id='Bestelbox' value='' name='AantalBestellen".$i."'></td>";
echo "<td width = 6%>" . htmlentities($row['AantalFustBesteld']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelenBesteld']) . "</td>";
135: echo '<td width = 8%><a href="Home.php?aanbodid='. htmlentities($row['aanbodid']) .'&hoeveelheid='. $_GET["AantalBestellen$i"]. '"'
. ' class = "btnBestel">Bestel</a></td></tr>';
$i = $i + 1;
}
The error I'm getting is undefined index. I guess this is because the name isn't unique. But whatever I do I still get the error.
I'm getting:
undefined index: AantalBestellen0 on line 135;
you can use javascript for example
note i will bold the code you need, the rest is context.
note this is from a similar project of mine but you should get the point.
<div id="meldingen_top_div">
<?php
echo "<div class='alert_Top_Div_Left_Outer'>
<input type='submit' value='Openstaande Meldingen' class='btnLoad' name='' onclick='toggleThis(" . '"' . "#meldTableTop" . '"' . "), toggleThis(".'"'.".alert_Top_Div_Left_Inner".'"'.")'/>
<div class='alert_Top_Div_Left_Inner'>
<table class='tableRed' id='meldTableTop'><caption/><thead/><tfoot/><tbody>";
$sqlVII = "SELECT Meldingen.Melding_id, FORMAT(Meldingen.Melding_datum, 'dd-mM-yyyy') AS Melding_datum, Producten.Product_naam, Leveranciers.Leverancier_naam, Meldingen.Melding_notitie
FROM MovieWorld.dbo.Producten,
MovieWorld.dbo.Meldingen,
MovieWorld.dbo.Categorieen,
MovieWorld.dbo.Leveranciers
WHERE Producten.Product_id = Meldingen.Product_id AND Producten.Categorie_id = Categorieen.Categorie_id AND Categorieen.Leverancier_id = Leveranciers.Leverancier_id AND Producten.Product_actief = 1 AND Meldingen.Melding_actief = 1
";
$resV= $db->executeQuery($sqlVII);
$i=1;
if($resV!=FALSE){
while($arrx = sqlsrv_fetch_array($resV)){
Code wich is relevant for you:
echo "<tr>
<td><p class='meldDate'>{$arrx['Melding_datum']}</p></td>
<td>{$arrx['Product_naam']}</td>
<td>{$arrx['Leverancier_naam']}</td>
<td><input id='txt{$i} type='text' name='thisdoesntevenmatter' value='..'/></td>
<td><img src='somerandompath.png' onclick='getTxt(".'"txt{$i}"'.")'/></td>
</tr>"
$i=$i+1;
}
}else{}echo '</tbody></table></div></div>';
?>
</div>
and the Javascript function
function getTxt(id){
var tempId = document.getElementById(id).value;
return tempId;
}
however.. you can also send the value back into a php variable, OR use AJAX to pass it to an PHP class to insert it into the Database.
edit
Your quotes in line 135: seem incorrect. try this:
echo '<td width = 8%><a href="Home.php?aanbodid={htmlentities($row['aanbodid']) }&hoeveelheid={$_GET['AantalBestellen$i']}"'
. ' class = "btnBestel">Bestel</a></td></tr>';
Where you get undefined index? on that $_POST['AantalBestellen'] ?
Use
if (isset($_POST['AantalBestellen'])) { }
to identify that the post value has been set
same do later for the hoeveelheid:
if (isset($_GET['hoeveelheid'])) { }
echo-ing the input field:
echo "<td width = 4%><input type ='text' id='Bestelbox' value='" . $_GET['hoeveelheid'] . "' name='AantalBestellen'></td>";
Also, dont forget to clear the spaces in:
'&hoeveelheid = '. $_POST //near the =

PHP regex undifined offset when used in function

I have a string consists of multiple lines. I am getting this string from imap (as an email body). I get this string as follows:
$mail_body = imap_fetchbody($mbox,$msgno,1);
My regex is:
preg_match("/HEX}(.*).php/", $string, $matches);
If I describe this string manually like:
$_string = "It is too long therefore I do not paste it here"
And If I do that:
preg_match("/HEX}(.*).php/",$_string,$matches);
$new_string = $matches[1];
echo $new_string;
It works perfectly.
But when I passed string to a function in same class:
$this->some_funtion($mail_body);
It gives me an error although I am doing the same thing in function:
preg_match("/HEX}(.*).php/",$_string,$matches);
$new_string = $matches[1];
echo $new_string;
Error: Notice: Undefined offset: 1
Why should it happen? I am doing the very same thing!
Thanks for your help!
EDIT
private function get_directory_path($string = '')
{
preg_match("/HEX}(.*).php/", $string, $matches);
$new_string = $matches[1];
echo $new_string;
}
I pass parameter as follows:
$mail_body = imap_fetchbody($mbox,$msgno,1.2);
if(!strlen($mail_body)>0){
$mail_body = imap_fetchbody($mbox,$msgno,1);
}
$this->get_directory_path($mail_body);
There are several things that might make the pattern not match. Newlines, spaces and tabs being the biggest problem because when you echo out to the screen and copy/paste to test they don't copy. Perhaps echo out the $mail_body variable inside of <pre> tags before passing it to the function or echo and view the source.
The easy way to fix it is to add the s modifier so that the dot (.) character matches newlines. So /pat{2}ern/s. But that might not give you the result you want. Without a full output of the string and what you expect from it (or what you are using it for), it wouldn't be possible to tell.
<?php
include('dataconn.php');
$result=mysql_query("select * from product");
while($row=mysql_fetch_assoc($result))
{
echo "<p>$row[Product_Name]</p>";
echo "<p>$row[Product_Quantity]</p>";
echo "<p>Add To Cart</p>";
}
?>
logout
/*--add to cart page--*/
<?php
/* ----------- ADD TO CART PAGE ----------------*/
include("dataconn.php");
$product_id = isset($_GET['pid']) ? $_GET['pid'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null; //the action
$quantity=isset($_GET['qty']) ? $_GET['qty'] : null;
?>
<html>
<head>
<title>View Cart</title>
</head>
<body>
<?php
$customer_id=$_SESSION['customer_id'];
$result=mysql_query("select * from product");
$row=mysql_fetch_assoc($result);
switch($action)
{
//decide what to do
case "add":
$_SESSION['cart'][$product_id]++;
break;
case "remove":
$_SESSION['cart'][$product_id] = 0;
unset($_SESSION['cart'][$product_id]);
header("Location: payment.php");//if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
header("Location: payment.php");
break;
}
//------- for checkout ---------
if(isset($_SESSION['cart']) && $_SESSION['cart']) {
$total = 0;
echo "<form name='cart' method='POST' action=''>";
echo "<table border=\"1\" padding=\"3\" width=\"100%\" class=\"data-container\">";
echo "<td colspan=\"4\" align=\"right\"><img src=\"image/delete.png\"/></td>";
foreach($_SESSION['cart'] as $product_id => $quantity)
{
$sql = sprintf("SELECT * FROM product WHERE Product_ID = %d;", $product_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$itemsInfo = mysql_fetch_assoc($result);
$cost = $itemsInfo["Product_Price"] * $quantity;
$total = $total + $cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">".$itemsInfo["Product_Name"]."</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity </td>";
echo "<td align=\"center\">RM $cost</td>";
echo "<td align=\"center\"><img src=\"image/remove.png\"/></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" ></td>";
echo "<td align=\"center\">Total</td>";
echo "<td colspan=\"2\" align=\"center\">RM $total</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
?>
<br>
<div>
<span style="margin-left: 88%"><input type="submit" name="shopping_more" class="custom-button" value="Back To Shopping"/></span>
</div>
</html>

How to display information in another PHP Page

I am having trouble with a mini shopping cart. I have created the mini shopping cart and when a product is added it goes into the Basket page. However, i want to create a checkout page. How do i grab the products in the basket and put it in a checkout page.
So For example, the check out page will look like this
ITEM NAME, ITEM MODEL, ITEM PRICE
TOTAL OF ITEMS
CHECKOUT BUTTON (links to a payment system)
This is my Basket.php code:
<?php
$bikecode = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
if($bikecode && !productExists($bikecode)) {
die("Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$bikecode]++; //add one to the quantity of the product with id $bikecode
break;
case "remove":
$_SESSION['cart'][$bikecode]--; //remove one from the quantity of the product with id $bikecode
if($_SESSION['cart'][$bikecode] == 0) unset($_SESSION['cart'][$bikecode]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
if($_SESSION['cart']){
echo "<table width=\"100%\">";
foreach($_SESSION['cart'] as $bikecode => $quantity) {
$sql = sprintf("SELECT BikeCode, Model, Price FROM Bike WHERE BikeCode = '%s';", $bikecode);
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
list($bikecode, $model, $price) = mysqli_fetch_row($result);
$cost = $quantity * $price;
$total = $total + $cost;
echo "<tr><th>BikeCode:</th><th>Model:</th><th>Quantity:</th><th>Price:</th></tr>";
echo "<tr>";
echo "<td align=\"center\">$bikecode</td>";
echo "<td align=\"center\">$model</td>";
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">£$cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Total</td>";
echo "<td align=\"right\">£$total</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"4\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
echo "You have no items in your shopping cart.";
}
function productExists($bikecode) {
$sql = sprintf("SELECT * FROM Bike WHERE BikeCode = '%s';", $bikecode);
return mysqli_num_rows(mysqli_query($con, $sql)) > 0;
}
?>
As long as you have a session_start(); on top of every page you should be able to use the exact same foreach loop as you do in this piece of coding. The session with the information would just be carried over to the next page.
Assume you have a page called test.php with the following code:
<?php
session_start();
$_SESSION['test'] = 1;
echo $_SESSION['test'];
?>
Then to access the test variable in othertest.php page,simply do the following:
<?php
session_start();
echo $_SESSION['test']; ?>
You forgot to add session_start() to the top of your php file. I recommend adding session_start() to a separate file and then including that file in each of the php pages that uses session variables.

Delete index session in PHP

I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you
I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data
Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.

How to display products under category [ data grouping ]

I am new to php-mysql. Can somebody help on the issue below? If so, please explain a bit so that I can learn. Thanks in advance.
$data=mysql_query("SELECT tbl_category.*, tbl_product.* FROM tbl_category LEFT JOIN tbl_product ON tbl_category.cat_id=tbl_product.cat_id ORDER BY tbl_category.cat_id");
$color="1";
while($fetch=mysql_fetch_array($data, MYSQL_ASSOC)){
if($fetch['cat_name'] != $category){ //this returns error: "Notice: Undefined variable: category in /.../filename.php on line [this line number]
$catdes = $fetch['pd_description'];
echo "<tr bgcolor='#A9F5F2'><td colspan=\"2\"><div align=\"center\"><br/><b>". $fetch['cat_name']."</b><br /><span class=\"itemdescription\">". $catdes."</div></div></td></tr>";
$category = $fetch['cat_name'];
}
$item = $fetch['pd_name'];
$desc = $fetch['pd_description'];
$price = $fetch['pd_price'];
if($color==1){
echo "<tr bgcolor='#FFFFFF'>";
echo "<td width=\"93%\"><div align=\"left\">";
echo $item . "<br /><span class=\"itemdescription\">";
echo $desc ;
echo "</div></td><td width=\"7%\" VALIGN=\"top\" ALIGN=\"right\"><div align=\"right\">";
echo $price ."</div></td><tr>";
$color="2";
}
else{
echo "<tr bgcolor='#F2F2F2'>";
echo "<td width=\"93%\"><div align=\"left\">";
echo $item . "<br /><span class=\"itemdescription\">";
echo $desc ;
echo "</div></td><td width=\"7%\" VALIGN=\"top\" ALIGN=\"right\"><div align=\"right\">";
echo $price ."</div></td><tr>";
$color="1";
}
}
That notice you received is the result of not declaring a variable before using it. It's always good practice to declare your variables before using them.
In your case you need to declare $category before comparing a value to it:
$category = '';
if($fetch['cat_name'] != $category){

Categories