Fetching array cart php - php

I have a following question. I store a shopping cart in an array session like below
session_start();
$id= $_GET['id'];
if(isset($_SESSION['cart']))
{
array_push($_SESSION['cart'], $id);
}
else
$_SESSION['cart']= array($id);
header("location:cart.php");
And when I try to retrieve the cart. I get the same product id as many as I put to the cart.
<?php
if(!isset($_SESSION['cart'])) {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
} else {
echo '<table border="0.2">';
$total_price = 0;
foreach($_SESSION['cart'] as $id) {
$the_query = "select * from products where id='$id' GROUP BY id";
$result = mysql_query($the_query) or die('Query failed: ' . mysql_error());
$the_product = mysql_fetch_array($result, MYSQL_ASSOC);
$total_price = $total_price + $the_product['price'];
$href = "show_products.php?id=".$the_product['id'];
//echo "<tr>";
echo "<tr><td><a href='$href'>";
echo "<img src='".$the_product['image_url_small']."' /></a></td>";
echo "<td><strong>".$the_product['name']."</strong></td><td><em>$".$the_product['price']."</em>";
echo "</td>";
echo "<td> <a href='do_deletecart.php?id=". $the_product['id'] ."'>Delete item </a></td></tr>";
}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
echo "</table>";
echo "<br /><a href='empty_cart.php'>Empty Cart</a> <a href='showallproducts.php'>Show phones</a><br /><br />";
}
how can I make it show only one product id or name. Thank in advance

If I understand your question correctly, you are getting many results for the same product id. This is because you are storing same id values many time in the $_SESSION variable.
You could do the following to not repeat the same ids in the $_SESSION variable.
EDIT
For sake of completeness I have updated the code. Hope that helps.
index.php
<?php
session_start();
$id= isset($_GET['id']) ? $_GET['id'] : null;
if(!is_null($id)){
if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){
// increment product quantity if already exists
// or create a new one
add_or_increment_product_to_cart($id, $_SESSION['cart']);
} else {
// initialize cart
// add the first product
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
}
function add_or_increment_product_to_cart($id, $cart){
foreach ($cart as $key => $product) {
if($id == $product->id){
$product->quantity++;
return;
}
}
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
header("location:cart.php");
Cart.php
<?php
session_start();
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : null;
if($cart) {
foreach ($cart as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id . " LIMIT 1";
// your code to fetch the products from the database
// what you have done is fine but vulnerable
// PDO recommended
}
} else {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
}
Also please note that mysql_connect is deprecated and PDO class is the recommended and safe way to connect to the database. Your code is vulnerable to SQL Injection like #Touki said in his comment.

I would recommend performing only one query to retrieve all of the products, and then iterate the result of the query to populate the HTML. For example;
$the_query = "select * from products where id in (". implode(',', $_SESSION['cart']) .")";
$result = mysql_query($the_query);
while (($the_product = mysql_fetch_array($result, MYSQL_ASSOC))) {
...
}
This has the added bonus that you only perform one query, and would also only select one row per product.
It's worth noting, however, that the mysql_* methods are deprecated, and it would be advisable to start using another library such as mysqli or PDO.
On a related note, this code currently is very liable to SQL injection, and the input should ideally be sanitised before being put into a query string.

Related

mysqi_* giving errors mysql_* didn't

I am new to php and I am in the process of changing a script from using mysql_* to mysqli_* functions. I am getting the following errors after switching:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in cart.php on line 115
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in cart.php on line 115
My code
<title>Cart</title>
<?php
require("../mysqli_connect.php");
?>
</head>
<body>
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //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;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
$product_id);
$result = mysqli_query($dbc, $sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysqli_num_rows($result) > 0) {
list($name, $description, $price) = mysqli_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$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 X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;",
$product_id);
return mysqli_num_rows(mysqli_query($dbc, $sql)) > 0; ***//this is line 15***
}
?>
Continue Shopping
<?php
/*
products table:
CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`description` TEXT,
`price` DOUBLE DEFAULT '0.00' NOT NULL ,
PRIMARY KEY ( `id` )
);
*/
?>
</body>
</html>
And here is the products page.
<title>Products</title>
<?php
require("../mysqli_connect.php");
?>
</head>
<body>
<table border="1">
<?php
$sql = "SELECT id, name, description, price FROM products;";
$result = mysqli_query($dbc, $sql);
while(list($id, $name, $description, $price) = mysqli_fetch_row($result)) {
echo "<tr>";
echo "<td>$name</td>";
echo "<td>$description</td>";
echo "<td>$price</td>";
echo "<td>Add To Cart</td>";
echo "</tr>";
}
?>
</table>
View Cart
</body>
</html>
Database connection
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'domain_user');
// Make the connection:
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbc, 'utf8');
Your connection is not making its way into the function. A quick fix is to mark the variable GLOBAL in your function.
function productExists($product_id) {
GLOBAL $dbc;
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $product_id);
return mysqli_num_rows(mysqli_query($dbc, $sql)) > 0;
}
This way $dbc is available in your function.
You MAY want to help make this a little more readable (at least to my eyes...)
function productExists($product_id) {
GLOBAL $dbc;
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $product_id);
$result = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
$rows = mysqli_num_rows($result);
return $rows;
}
I've found it to be easier to read the two lines in place of nesting the functions into one.

Challenges with mysql_fetch_array()

I'm running into a situation where a mysql_query() result being fed into a mysql_fetch_array() function is being interpreted as a boolean instead of the result.
The below code uses Using an SQL result in a foreach loop as a coding example for doing a foreach loop. There may be multiple problems with the code still as my current problem occurs before the foreach loop.
$results=mysql_query("SELECT * FROM order_details WHERE orderid = $orderid");
print "SELECT * FROM order_details WHERE orderid = $orderid";
$productid;
$quantity;
$price;
$resultset = array();
while ($row = mysql_fetch_arraY($results)) {
$resultset[] = $row;
}
foreach ($resultset as $result)
{
$productid = $result['productid'];
$quantity = $result['quantity'];
$price = $result['price'];
print "<br />$productid, $quantity, $price";
};
Change $orderid to '$orderid' provided that everything is fine.
One big note, try going over mysqli and PDO instead of mysql.
for($i=0;$i<$max;$i++) {
$pid=$_SESSION['cart'][$i]['productid'];
$q=$_SESSION['cart'][$i]['qty'];
$price=get_price($pid);
$pname;
$row = mysql_fetch_assoc(mysql_query("SELECT name\n"
. "FROM `products` \n"
. "WHERE SERIAL =$pid\n"
. "LIMIT 1"));
$pname = $row['name'];
print "<br />Product Name: $pname, Quantity: $q, Price: $price";
}

code to add to favourites fails silently

I have a myList.php which should list all products added to my favourites and compute the total price of products.
here is the code:
<?php
include 'navigation.php'
?>
<div class='sectionContents'>
<?php
if (isset($_GET['action']) && $_GET['action'] == 'removed') {
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
if (isset($_SESSION['fav'])) {
$ids = "";
foreach($_SESSION['fav'] as $prod_id) {
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
include "db_connect.php";
$query = mysql_query("SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')") or die(mysql_error());
$num = mysql_num_rows($query);
if ($num > 0) {
echo "<table border='0'>"; //start table
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (MUR)</th>";
echo "<th>Action</th>";
echo "</tr>";
//also compute for total price
$totalPrice = 0;
while ($row = mysql_fetch_assoc($query)) {
extract($row);
$totalPrice += $prod_price;
//creating new table row per record
echo "<tr>";
echo "<td>{$prod_name}</td>";
echo "<td class='textAlignRight'>{$prod_price}</td>";
echo "<td class='textAlignCenter'>";
echo "<a href='remove_favourite.php?prod_id= {$prod_id}&prod_name={$prod_name}' class='customButton'>";
echo "<img src='shopping-cart-in-php/images/remove-from- cart.png' title='Remove from favourite' />";
echo "</a>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<th class='textAlignCenter'>Total Price</th>";
echo "<th class='textAlignRight'>{$totalPrice}</th>";
echo "<th></th>";
echo "</tr>";
echo "</table>";
echo "<br /><div><a href='#' class='customButton'>Home</a></div>";
} else {
echo "<div>No products found in your favourites. :(</div>";
}
} else {
echo "<div>No products in favourites yet.</div>";
}
?>
I use the add_to_fav.php below to add the products to my favourites:
<?php
session_start();
// get the product id
$prod_id = $_GET['prod_id'];
$prod_name = $_GET['prod_name'];
/*
* check if the 'fav' session array was created
* if it is NOT, create the 'fav' session array
*/
if (!isset($_SESSION['fav'])) {
$_SESSION['fav'] = array();
}
// check if the item is in the array, if it is, do not add
if (in_array($prod_id, $_SESSION['fav'])) {
// redirect to product list and tell the user it was added to favourites
header('Location: prod_list.php?action=exists&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
// else, add the item to the array
else {
array_push($_SESSION['fav'], $prod_id);
// redirect to product list and tell the user it was added to cart
header('Location: prod_list.php?action=add&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
?>
I am having "No products found in your favourites. :(" when i try to view the favourites
I have a counter like thing which shows the number of products in my favourites as well and it stays to 0.
Have I erred somewhere? Which mistake should I correct?
There are a few things that could be happening.
1) You are not starting the session before loading the favorites:
<div class='sectionContents'>
<?php
if(isset($_GET['action']) && $_GET['action']=='removed'){
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
session_start()
if(isset($_SESSION['fav'])){
2) Your SQL query in fact is not finding any product ids. You might want to debug the SQL and run it in phpmyadmin or your mysql interface to see if it in fact does return any results.
include "db_connect.php";
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')";
echo $query; // Print query for debugging
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
My guess is that this query is incorrect because of the single quotes around $ids
It should be:
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ($ids)";
Also this can be simplified from:
$ids = "";
foreach($_SESSION['fav'] as $prod_id){
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
To:
$ids = implode(",", $_SESSION['fav']);

Can not get the id from the cart session

I'm working on my homework. I have a cart session and I can get on the attribute in mySql database base on the product id.
<?php
$total_price=0;
if(isset($_SESSION['cart']) ? $_SESSION['cart'] : null)
{
echo "<tr>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
</tr>";
foreach ($_SESSION['cart'] as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id;
$the_product = $db->query($the_query) or die('Query failed: '.mysql_error());
$the_product->execute();
$the_product->setFetchMode(PDO::FETCH_OBJ);
while ($row = $the_product->fetch()){
$total_price = $total_price + $row->price*$product->quantity;
echo "<tr><td>";
echo "<img src='".$row->image_url_small."' /></a></td>";
echo "<td><strong>".$row->name."</strong></td><td><em>$".$row->price."</em>";
echo '</td>';
echo '<td><input type="text" id="'.$row->id.'" class="override" value="'.$product->quantity.'"/></td>';
echo '<td>Delete item </td></tr>';
}}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
}
else {
echo "Your cart is empty.";
}
?>
Update
I can pass the id to do_deletecart.php. But now I can delete the product from cart
do_deletecart.php
<?php
session_start();
$product = $_GET['id'];
foreach($_SESSION['cart'] as $key=>$value) {
if($product == $value)
{
unset($_SESSION['cart'][$key]);
break;
} }
header("location:cart.php");
?>
Well, assuming that $row->id contains what you expect, you have enclosed it with quote marks, which will essentially terminate the <a> element's href attribute.
You need to update your code as follows:
echo '<td>Delete item </td></tr>';
Also, you might want to check that you have actually started the session. In order to access the $_SESSION superglobal, you need to first have called session_start() before any output was sent to the browser.
You need to make sure you include
session_start(); before using $_SESSION

insert data into database for shopping cart

I am doing a shopping cart and I am not sure where or rather which page do I code my INSERT INTO statement.
viewProducts.php
<?php
if (isset($_SESSION['cartCity'])) {
$sql = "SELECT * FROM productsc WHERE id_product IN (";
foreach ($_SESSION['cartCity'] as $id => $value) {
$sql .= $id . ",";
}
$sql = substr($sql, 0, -1) . ") ORDER BY id_product ASC";
$query = mysql_query($sql);
if (!empty($query)) {
while ($row = mysql_fetch_assoc($query)) {
?>
<p><?php echo $row['name']; ?><?php echo " x " . $_SESSION['cartCity'][$row['id_product']]['quantity']; ?></p>
<?php
}
} else {
echo "<i>You need to add an item to your cart for it to be visible here</i><br />";
}
} else {
echo "<p>Your cart is empty. <br/> Please add some products</p>";
}
echo "<a href='viewProductsCity.php?page=cartCity'>Go to Cart</a>";
echo "<a href='checkout.php'>Checkout</a>";
?>
or should i add in cart or viewAdd(this is where the codes for when the customer clicks on add to cart button runs) page?
I would create a separate page to do that.
Then, I would include it just by redirecting the user there or by calling it with AJAX. When user got the cart with something, then yeah, we would redirect him to the checkout, and ask him if he wants to buy now or keep shopping.

Categories