/    Sign up×
Community /Pin to ProfileBookmark

Coding problem,please help

[code=php]//function.inc.php

<?php
function writeShoppingCart() {
$cart = $_SESSION[‘cart’];
if (!$cart) {
return ‘<p>You have no items in your shopping basket</p>’;
} else {
// Parse the cart session variable
$items = explode(‘,’,$cart);

return ‘<p>You have <a href=”cart.php”>’.count($items).’ item in your shopping cart</a></p>’;
}
}

function showCart() {

$db=new mysqli(‘localhost’,’root’,”);

if(mysqli_connect_errno())
{
die(‘Connect failed:’.mysqli_connect_error());
}

$db->select_db(‘test’)
or die(‘select_db failed:’.$db->error);

$cart = $_SESSION[‘cart’];
if ($cart) {
$items = explode(‘,’,$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = ‘<form action=”cart.php?action=update” method=”post” id=”cart”>’;
$output[] = ‘<table>’;
foreach ($contents as $id=>$qty) {

$query=’SELECT * FROM books WHERE id = ‘.$id;
$result=$db->query($query)
or die(‘query failed’.$db->error);

$row = $result->fetch_assoc();
extract($row);
$output[] = ‘<tr>’;

$output[] = ‘<td>’.$title.’ by ‘.$author.'</td>’;
$output[] = ‘<td>RM’.$price.'</td>’;

$output[] = ‘<td><a href=”cart.php?action=delete&id=’.$id.'”>Remove</a></td>’;
$total += $price;
$output[] = ‘</tr>’;
}
$output[] = ‘</table>’;
$output[] = ‘<p>Grand total: <strong> RM’.$total.'</strong></p>’;
//$output[] = ‘<div><button type=”submit”>Update cart</button></div>’;
$output[] = ‘</form>’;
} else {
$output[] = ‘<p>You shopping cart is empty.</p>’;
}
return join(”,$output);
}
?>
————————————————————-
//cart.php

<?php

// Include functions
require_once(‘inc/functions.inc.php’);
// Start the session
session_start();
// Process actions
$cart = $_SESSION[‘cart’];
$action = $_GET[‘action’];
switch ($action) {
case ‘add’:
if ($cart){

if($cart!=$_GET[‘id’]){

$cart .= ‘,’.$_GET[‘id’];
}

else{

echo “you already order the book!”;
}

}

else{

$cart = $_GET[‘id’];

}
break;
case ‘delete’:
if ($cart) {
$items = explode(‘,’,$cart);

$newcart = ”;
foreach ($items as $item) {
if ($_GET[‘id’] != $item) {
if ($newcart != ”) {
$newcart .= ‘,’.$item;
} else {
$newcart = $item;
}
}
}
$cart = $newcart;
}
break;
}
$_SESSION[‘cart’] = $cart;
?>

<body>

<h1>Your Shopping Cart</h1>

<?php
echo writeShoppingCart();
?>

<h1>You have order the following book</h1>

<?php
echo showCart();
?>

<p><a href=”index.php”>Order More Book</a></p>

</body>
</html>
—————————————————-
//index.php

<?php

// Include functions
require_once(‘inc/functions.inc.php’);
// Start the session
session_start();
?>

<body>

<h1>Your Shopping Cart</h1>

<?php
echo writeShoppingCart();
?>

<h1>Books In Our Store</h1>

<?php
$db=new mysqli(‘localhost’,’root’,”);

if(mysqli_connect_errno())
{
die(‘Connect failed:’.mysqli_connect_error());
}

$db->select_db(‘test’)
or die(‘select_db failed:’.$db->error);

$query=’SELECT * FROM books ORDER BY id’;;

$result=$db->query($query)
or die(‘query failed’.$db->error);

$output[] = ‘<ol>’;
while ($row = $result->fetch_assoc()) {
$output[] = ‘<li>”‘.$row[‘title’].'” by ‘.$row[‘author’].’: RM’.$row[‘price’].'<br /><a href=”cart.php?action=add&id=’.$row[‘id’].'”>Add to cart</a></li>’;
}
$output[] = ‘</ol>’;
echo join(”,$output);
?>

</body>
</html>[/code]

—————————

CREATE TABLE books(
id int auto_increament,
title varchar
author varchar
price decimal
PRIMARY KEY(id)

)
———————————————————-

examples:

INSERT INTO books VALUES(1,’ABC’,’kelly’,’25.00′);
INSERT INTO books VALUES(2,’XYZ’,’john’,’80.00′);


——————————————————

my Question:

I am using MySQL+PHP5+IIS

(*NOTE:i just let the user to buy each book for ONE unit only.)

step 1(correct):

when i click “Add to cart”(index.php) for the book “ABC” ,
a message was shown in (cart.php):”You have 1 item in your shopping basket”
when i click the “Add to cart”(index.php) for the book “ABC” AGAIN,
a message shown including:”You have 1 item in your shopping basket” and
“you already order the book!”

step 2(have bugs/error occur):

when i click “when i click “Add to cart”(index.php) for the book “XYZ” ,
a message was shown in (cart.php):”You have 2 item in your shopping basket”
when i click the “Add to cart”(index.php) for the book “ABC” AGAIN,
a message shown including:”You have 3 item in your shopping basket”
(*the item number will continue increase)

what i want is:i hope i can get the message “You have 2 item in your shopping basket”
Also,will shown “you already order the book!” when i try to add the same item again!

The coding part that i suspect make the error occur as below:

case ‘add’:
if ($cart){

if($cart!=$_GET[‘id’]){
$cart .= ‘,’.$_GET[‘id’];
}
else{
echo “you already order the book!”;
}
}

else{

$cart = $_GET[‘id’];

}

—>can anyone help me to edit it?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@themartyFeb 05.2007 — You shouldn't save the items in a comma seperated string in your session variable, but create an array of them

so whenever you add an item:

[code=php]
function addItem($itemID, $itemName, $itemPrice)
{
$_SESSION['cart'][$itemID] = array("name"=>$itemName, "price"=>$itemPrice);
}
[/code]


this will allow you to do the following:
[code=php]
function addItem($itemID, $itemName, $itemPrice)
{
if (!array_key_exists($itemID, $_SESSION['cart']))
$_SESSION['cart'][$itemID] = array("name"=>$itemName, "price"=>$itemPrice);
else
echo "error: you already have ".$_SESSION['cart'][$itemID]['name']." in your cart";
}
[/code]


note that this is just an example!
Copy linkTweet thisAlerts:
@ctyauthorFeb 11.2007 — I hope you can show me how to edit the coding using your coding.Thanks
×

Success!

Help @cty spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...