Wrox Programmer Forums
|
Javascript General Javascript discussions.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Javascript section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old August 30th, 2011, 09:39 AM
Authorized User
 
Join Date: Jul 2011
Posts: 49
Thanks: 0
Thanked 0 Times in 0 Posts
Default shopping cart problem

hi all,
i am working on a simple shopping cart program.I have created one database and stored images too in database.
i am not getting executed the shopping cart.tell me what went wrong.
below is my database i have created......
it is saved as "shopping.sql"
SQL Code:
-- Table structure for table `customers`

CREATE TABLE IF NOT EXISTS `customers`(
  `serial` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) collate latin1_general_ci NOT NULL,
  `email` varchar(80) collate latin1_general_ci NOT NULL,
  `address` varchar(80) collate latin1_general_ci NOT NULL,
  `phone` varchar(20) collate latin1_general_ci NOT NULL,
  PRIMARY KEY(`serial`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

-- Table structure for table `orders`

CREATE TABLE IF NOT EXISTS `orders` (
  `serial` int(11) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `customerid` int(11) NOT NULL,
  PRIMARY KEY(`serial`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;
-- Dumping data for table `orders`

-- Table structure for table `order_detail`
CREATE TABLE IF NOT EXISTS `order_detail` (
  `orderid` int(11) NOT NULL,
  `productid` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `price` float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
-- Dumping data for table `order_detail`

-- Table structure for table `products`
CREATE TABLE IF NOT EXISTS `products`(
  `serial` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) collate latin1_general_ci NOT NULL,
  `description` varchar(255) collate latin1_general_ci NOT NULL,
  `price` float NOT NULL,
  `picture` varchar(80) collate latin1_general_ci NOT NULL,
  PRIMARY KEY(`serial`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=7;

INSERT INTO `products` (`serial`, `name`, `description`, `price`, `picture`) VALUES
(1, 'View Sonic LCD', '19" View Sonic Black LCD, with 10 months warranty', 250, 'images/lcd.jpg'),
(2, 'IBM CDROM Drive', 'IBM CDROM Drive', 80, 'images/cdrom-drive.jpg'),
(3, 'Laptop Charger', 'Dell Laptop Charger with 6 months warranty', 50, 'images/charger.jpg'),
(4, 'Seagate Hard Drive', '80 GB Seagate Hard Drive in 10 months warranty', 40, 'images/hard-drive.jpg'),
(5, 'Atech Mouse', 'Black colored laser mouse. No warranty', 5, 'images/mouse.jpg'),
(6, 'Nokia 5800', 'Nokia 5800 XpressMusic is a mobile device with 3.2" widescreen display brings photos, video clips and web content to life', 299, 'images/mobile.jpg');

below is my database connection saved ad "db.php"
Code:
<?php
mysql_connect("localhost","root","") or die("mysql_error()");
mysql_select_db("shopping") or die("mysql_error()");
session_start();
?>
below is my "functions.php" program
Code:
<?php
function get_product_name($pid)
 {
  $result=mysql_query("select name from products where serial=$pid");
  $row=mysql_fetch_array($result);
  return $row['name'];
 }

function get_price($pid)
 {
  $result=mysql_query("select price from products where serial=$pid");
  $row=mysql_fetch_array($result);
  return $row['price'];
 }

function remove_product($pid)
 {
  $pid=intval($pid);
  $max=count($_SESSION['cart']);
  for($i=0;$i<$max;$i++)
   {
    if($pid==$_SESSION['cart'][$i]['productid'])
     {
	unset($_SESSION['cart'][$i]);
	break;
     }
   }
    $_SESSION['cart']=array_values($_SESSION['cart']);
 }

function get_order_total()
{
 $max=count($_SESSION['cart']);
 $sum=0;
 for($i=0;$i<$max;$i++)
 {
  $pid=$_SESSION['cart'][$i]['productid'];
  $q=$_SESSION['cart'][$i]['qty'];
  $price=get_price($pid);
  $sum+=$price*$q;
 }
return $sum;
}

function addtocart($pid,$q)
 {
  if($pid<1 or $q<1) return;
  if(is_array($_SESSION['cart']))
   {
    if(product_exists($pid)) return;
    $max=count($_SESSION['cart']);
    $_SESSION['cart'][$max]['productid']=$pid;
    $_SESSION['cart'][$max]['qty']=$q;
   }
    else
     {
      $_SESSION['cart']=array();
      $_SESSION['cart'][0]['productid']=$pid;
      $_SESSION['cart'][0]['qty']=$q;
     }
 }
	
function product_exists($pid)
 {
  $pid=intval($pid);
  $max=count($_SESSION['cart']);
  $flag=0;
  for($i=0;$i<$max;$i++)
  {
   if($pid==$_SESSION['cart'][$i]['productid'])
    {
     $flag=1;
     break;
    }
  }
return $flag;
 }
?>
below is the "products.php".this is the program from where my shopping cart begins.here i am not getting displayed the product image,price.and "addtocart" button is also not executing.
Code:
<?php
include("db.php");
include("functions.php");
if($_REQUEST['command']=='add' && $_REQUEST['productid']>0)
 {
  $pid=$_REQUEST['productid'];
  addtocart($pid,1);
  header("location:shoppingcart.php");
  exit();
 }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Products</title>
<script type="text/javascript">
function addtocart(pid)
 {
  document.form1.productid.value=pid;
  document.form1.command.value='add';
  document.form1.submit();
 }
</script>
</head>
<body>
<form name="form1">
<input type="hidden" name="productid" />
<input type="hidden" name="command" />
</form>
<div align="center">
<h1 align="center">Products</h1>
<table border="0" cellpadding="2px" width="600px">
<?php
 $result=mysql_query("select * from products");
 while($row=mysql_fetch_array($result))
  {
?>
   <tr>
    <td><img src="<?php=$row['picture']?>" /></td>
    <td><b>       <?php=$row['name']?></b><br />
                  <?php=$row['description']?><br />
				  Price:<big style="color:green">
                 $<?php=$row['price']?></big><br /><br />
       <input type="button" value="Add to Cart" onclick="addtocart(<?php=$row['serial']?>)" />
	</td>
	</tr>
      <tr><td colspan="2"><hr size="1" /></td></tr>
       <?php
 } 
       ?>
</table>
</div>
</body>
</html>
below is my "shoppingcart.php" program after selecting no of items for shopping the below program id displayed.
Code:
<?php
include("db.php");
include("functions.php");
if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0)
 {
  remove_product($_REQUEST['pid']);
 }
else if($_REQUEST['command']=='clear')
 {
  unset($_SESSION['cart']);
 }
else if($_REQUEST['command']=='update')
 {
  $max=count($_SESSION['cart']);
  for($i=0;$i<$max;$i++)
   {
    $pid=$_SESSION['cart'][$i]['productid'];
    $q=intval($_REQUEST['product'.$pid]);
    if($q>0 && $q<=999)
     {
	$_SESSION['cart'][$i]['qty']=$q;
     }
	else
     {
	  $msg='Some products not updated!,quantity must be a number between 1 and 999';
	 }
   }
 }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<script type="text/javascript">
function del(pid)
{
 if(confirm('Do you really mean to delete this item?'))
   {
    document.form1.pid.value=pid;
    document.form1.command.value='delete';
    document.form1.submit();
   }
}

function clear_cart()
{
 if(confirm('This will empty your shopping cart, continue?'))
  {
    document.form1.command.value='clear';
    document.form1.submit();
  }
}

function update_cart()
 {
  document.form1.command.value='update';
  document.form1.submit();
 }

</script>
</head>
<body>
<form name="form1" method="post">
<input type="hidden" name="pid" />
<input type="hidden" name="command" />
<div style="margin:0px auto; width:600px;" >
  <div style="padding-bottom:10px">
   <h1 align="center">Your Shopping Cart</h1>
   <input type="button" value="Continue Shopping" onclick="window.location='products.php'" />
  </div>
    <div style="color:#F00"><?php=$msg?></div>
    <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
    <?php
    if(is_array($_SESSION['cart']))
      {
        echo '<tr bgcolor="#FFFFFF" style="font-weight:bold">
	    <td>Serial</td>
	    <td>Name</td>
		<td>Price</td>
		<td>Qty</td>
	    <td>Amount</td>
		<td>Options</td></tr>';
	    $max=count($_SESSION['cart']);
	     for($i=0;$i<$max;$i++)
          {
		 $pid=$_SESSION['cart'][$i]['productid'];
		 $q=$_SESSION['cart'][$i]['qty'];
		 $pname=get_product_name($pid);
		 if($q==0) continue;
	?>
  <tr bgcolor="#FFFFFF"><td><?php=$i+1?></td><td><?php=$pname?></td>
     <td>$ <?php=get_price($pid)?></td>
     <td><input type="text" name="product<?php=$pid?>" value="<?php=$q?>" maxlength="3" size="2" /></td>
     <td>$ <?php=get_price($pid)*$q?></td>
     <td><a href="javascript:del(<?php=$pid?>)">Remove</a></td>
  </tr>
 <?php
 }
 ?>
	<tr>
	<td><b>Order Total: $<?php=get_order_total()?></b></td>
	<td colspan="5" align="right">
	<input type="button" value="Clear Cart" onclick="clear_cart()">
    <input type="button" value="Update Cart" onclick="update_cart()">
    <input type="button" value="Place Order" onclick="window.location='billing.php'">
	</td>
	</tr>
  <?php
      }
	else
     {
	echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
	}
	?>
     </table>
   </div>
</form>
</body>
</html>
this is the final "billing.php".if only user name is given it will execute.
but i want all things to be mandatory.
Code:
<?php
include("db.php");
include("functions.php");
if($_REQUEST['command']=='update')
{
  $name=$_REQUEST['name'];
  $email=$_REQUEST['email'];
  $address=$_REQUEST['address'];
  $phone=$_REQUEST['phone'];
  $result=mysql_query("insert into customers values('','$name','$email','$address','$phone')");
  $customerid=mysql_insert_id();
  $date=date('Y-m-d');
  $result=mysql_query("insert into orders values('','$date','$customerid')");
  $orderid=mysql_insert_id();	
  $max=count($_SESSION['cart']);
  for($i=0;$i<$max;$i++)
   {
    $pid=$_SESSION['cart'][$i]['productid'];
    $q=$_SESSION['cart'][$i]['qty'];
    $price=get_price($pid);
    mysql_query("insert into order_detail values($orderid,$pid,$q,$price)");
   }
	die('Thank You! your order has been placed!');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Billing Info</title>
<script type="text/javascript">
 function validate()
  {
	var f=document.form1;
	 if(f.name.value=='')
      {
		alert('Your name is required');
		f.name.focus();
		return false;
	  }
		f.command.value='update';
		f.submit();
 }
</script>
</head>
<body>
<form name="form1" onsubmit="return validate()">
    <input type="hidden" name="command" />
	<div align="center">
        <h1 align="center">Billing Info</h1>
        <table border="0" cellpadding="2px">
         <tr><td>Order Total:</td><td><?=get_order_total()?></td></tr>
         <tr><td>Your Name:</td><td><input type="text" name="name" /></td></tr>
         <tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
         <tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
         <tr><td>Phone:</td><td><input type="text" name="phone" /></td></tr>
         <tr><td>&nbsp;</td><td><input type="submit" value="Place Order" /></td></tr>
        </table>
	</div>
</form>
</body>
</html>
tell me what went wrong why it is not executing....
 
Old September 1st, 2011, 04:40 AM
Authorized User
 
Join Date: Jan 2011
Posts: 86
Thanks: 1
Thanked 12 Times in 12 Posts
Default

Hi ravi,


not sure what your problem is here .

But as it looks you need to make all form fields mandatory, or your database insert fails (as all customers database fields do not allow nulls).

You currently only validate the name field with your javascript, you could expand that logic as follows to make all your fields mandatory:

Code:
<script type="text/javascript">
 function validate()
  {
	var f=document.form1;
	var fel;
	var errmsg = 'Fill in all the required fields:\n\n';
	var ec = 0;
	if(f.name.value=='')
	{
		errmsg = errmsg + ' - Your Name\n';
		ec++;
		if (typeof(fel) == 'undefined')
			fel = f.name;
	}
	if (f.address.value=='')
	{
		errmsg = errmsg + ' - Address\n';
		ec++;
		if (typeof(fel) == 'undefined')
			fel = f.address;
	}
	if (f.email.value=='')
	{
		errmsg = errmsg + ' - Email\n';
		ec++;
		if (typeof(fel) == 'undefined')
			fel = f.email;
	}
	if (f.phone.value=='')
	{
		errmsg = errmsg + ' - Phone\n';
		ec++;
		if (typeof(fel) == 'undefined')
			fel = f.phone;
	}
	if (ec > 0) {
		alert(errmsg);
		fel.focus();
		return false;
	} else {
		f.command.value='update';
		return true;
	}
 }
</script>
Hope this helps
 
Old September 2nd, 2011, 08:41 AM
Authorized User
 
Join Date: Jul 2011
Posts: 49
Thanks: 0
Thanked 0 Times in 0 Posts
Default reply

hi ,
for the above shopping cart written in php and html whether it is possible to do in JQUERY and CSS and and by javascript...
kindly tell me how to do with JQUERY and CSS for looking much better.....





Similar Threads
Thread Thread Starter Forum Replies Last Post
shopping cart problem...! preetham.sarojavenkatesh Visual Studio 2005 1 November 13th, 2007 12:29 PM
Problem With Total in the Shopping Cart learningASP.Net BOOK: ASP.NET 2.0 Website Programming Problem Design Solution ISBN: 978-0-7645-8464-0 1 October 27th, 2007 09:33 AM
shopping cart problem Adam H-W Javascript 2 November 14th, 2006 12:57 PM
Problem with session on Shopping Cart comicghozt .NET Framework 1.x 6 September 21st, 2006 09:22 AM
having problem with shopping cart radonfile Classic ASP Databases 0 September 26th, 2003 12:42 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.