Jump to content

A non ending querry for php experts


riddhi

Recommended Posts

I have developed a budget.php where the customer may shop after the price

range. Some relavant part of the code is as follows:-

 

<label>Enter Amount (in $)  
      <input name="cost" type="text" value="0"/>
  </label> 
  <p>
    <label>Please Select a Category
    <select name="category">
      <option>Select a Category</option>

      <?	     
	    while ($row=mysql_fetch_array($res)){
		      echo "<option value={$row['cat_id']}>
		         {$row['cat_name']}</option>"; 
	     }
	?>
    </select>
</label>
</p>

<p> 
    <input name="submit" type="submit"value="Search"/>
    <input name="reset" type="reset" value="Reset"/>
  </p>
</form>
</center>

<p>
  <?
  extract($_POST); // Extracts POST Gobal Array 
  global $total,$price,$pos;
   	  	      
if(isset($submit)){
   err_after_submission();// Checks errors After submission

   if(ereg("[0-9]",$category)){ 
           // Checks Numeric Entry by user

 $res=dbQuery("SELECT B.PD_THUMBNAIL,B.PD_NAME, 
               B.PD_DESCRIPTION,B.PD_QTY,B.PD_PRICE 
 			   FROM  TBL_CATEGORY A, TBL_PRODUCT B
                   WHERE A.cat_Parent_ID=$category 
			   AND A.CAT_ID=B.CAT_ID 
			   ORDER BY B.PD_PRICE");

   echo " <br><br> <b> <center> Search Result </center></b>";
  		
   $price=$cost; //Backup data
   $total=0; // Contains Total Cost of the Product

 while ($record=mysql_fetch_array($res)){
				 	     	  	 
	if($record['PD_PRICE'] <= $price) 
	 {// Display the Product if within the Price Range 

	     echo "<table cellpadding='5', 

border='5',cellspacing='10' align='center'>
		   	   <br><b><center>Product Details </center> 

</b>";
		 echo "<br><tr> <td> Preview </td> <td> Name </td>";
		 echo "<td> Description </td> <td> Quantity 

Available</td>";
         echo "<td>Price</td>";
	     echo "<tr>";
		   
	    $total=$total + $record['PD_PRICE'];
	  	$price=$price - $record['PD_PRICE'];

	 	if($record['PD_THUMBNAIL']){
	        $cat_image=$record['PD_THUMBNAIL'];
	        
			if($cat_image)
	           $cat_image = WEB_ROOT.'images/product/' . 

$cat_image;
	        else 
		       $cat_image = 

WEB_ROOT.'images/no-image-small.png';
		     	    
			echo " <td width='75' align='center'><img 

src='$cat_image'>";		
		 }// End of Thumbnail IF
	     
            echo "<b>";   			   
	    echo "<td>$record[PD_NAME]</td>";
	    echo "<td>$record[PD_DESCRIPTION]</td>";
		echo "<td>$record[PD_QTY]</td>";
		echo "<td>$record[PD_PRICE]</td>";
		echo "</b>";		  
	  	echo "</tr>";	 
	}// ENDIF
   else{
      echo "<br><br><marquee bgcolor='red'>
	        <b>No Product in The Category Within the Entered 

Amount</b></marquee>"; 
	  exit;		  
   }		
}// End While 

  echo "</table>";
  
  echo "<br /><br />";
      echo " <div align='right' ";
      echo "<form name='form1' method='post' action='cart.php'>";
      echo "<input type='submit' value='Checkout' />";
      echo "</form>";
      echo "</div>";

  }// End IF Category
}// End IF Submit 

  
function err_after_submission(){ 	
      global $cost,$category;
    
  if(!ereg("[0-9]",$cost)) {
	  // Prevents alphabet or invalid number Entry
       echo "<br> <center> INVALID ENTRY!!!"
	       ." Please Enter a Number... </center>";
	  } 
     
 if( $cost==0 || $cost < 0){
      echo "<br> <center> INVALID ENTRY!!!"
	       ." Please Enter a Valid Number... </center>";
	  } 
 	  
 if(ereg("Select a Category",$category)){
	 // Not Even a Single Category Selected
       echo "<br><center>Please Select a Category</center>";
  } 
  } // End of Error Routine	  	
?>
</p>
<p> </p>
<p>  </p>
<p>  </p>
<p>    </p>
<p>   </p>
</body>
</html>

 

I want to transer the selected item when the user press checkout to the

following code:-CART.PHP

 

<?php
require_once 'library/config.php';
require_once 'library/cart-functions.php';

$action = (isset($_GET['action']) && $_GET['action'] != '') ? $_GET['action'] 

: 'view';

switch ($action) {
case 'add' :
	addToCart();
	break;
case 'update' :
	updateCart();
	break;	
case 'delete' :
	deleteFromCart();
	break;
case 'view' :
}

$cartContent = getCartContent();
$numItem = count($cartContent);

$pageTitle = 'Shopping Cart';
require_once 'include/header.php';

// show the error message ( if we have any )
displayError();

if ($numItem > 0 ) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'] . "?action=update"; ?>" 

method="post" name="frmCart" id="frmCart">
<table width="780" border="0" align="center" cellpadding="5" cellspacing="1" 

class="entryTable">
  <tr class="entryTableHeader"> 
   <td colspan="2" align="center">Item</td>
   <td align="center">Unit Price</td>
   <td width="75" align="center">Quantity</td>
   <td align="center">Total</td>
  <td width="75" align="center"> </td>
</tr>
<?php
$subTotal = 0;
for ($i = 0; $i < $numItem; $i++) {
extract($cartContent[$i]);
$productUrl = "index.php?c=$cat_id&p=$pd_id";
$subTotal += $pd_price * $ct_qty;
?>
<tr class="content"> 
  <td width="80" align="center"><a href="<?php echo $productUrl; ?>"><img 

src="<?php echo $pd_thumbnail; ?>" border="0"></a></td>
  <td><a href="<?php echo $productUrl; ?>"><?php echo $pd_name; ?></a></td>
   <td align="right"><?php echo displayAmount($pd_price); ?></td>
  <td width="75"><input name="txtQty[]" type="text" id="txtQty[]" size="5" 

value="<?php echo $ct_qty; ?>" class="box" onKeyUp="checkNumber(this);">
  <input name="hidCartId[]" type="hidden" value="<?php echo $ct_id; ?>">
  <input name="hidProductId[]" type="hidden" value="<?php echo $pd_id; ?>">
  </td>
  <td align="right"><?php echo displayAmount($pd_price * $ct_qty); ?></td>
  <td width="75" align="center"> <input name="btnDelete" type="button" 

id="btnDelete" value="Delete" onClick="window.location.href='<?php echo 

$_SERVER['PHP_SELF'] . "?action=delete&cid=$ct_id"; ?>';" class="box"> 
  </td>
</tr>
<?php
}
?>
<tr class="content"> 
  <td colspan="4" align="right">Sub-total</td>
  <td align="right"><?php echo displayAmount($subTotal); ?></td>
  <td width="75" align="center"> </td>
</tr>
<tr class="content"> 
   <td colspan="4" align="right">Shipping </td>
  <td align="right"><?php echo displayAmount($shopConfig['shippingCost']); 

?></td>
  <td width="75" align="center"> </td>
</tr>
<tr class="content"> 
   <td colspan="4" align="right">Total </td>
  <td align="right"><?php echo displayAmount($subTotal + 

$shopConfig['shippingCost']); ?></td>
  <td width="75" align="center"> </td>
</tr>  
<tr class="content"> 
  <td colspan="5" align="right"> </td>
  <td width="75" align="center">
<input name="btnUpdate" type="submit" id="btnUpdate" value="Update Cart" 

class="box"></td>
</tr>
</table>
</form>
<?php
} else {

?>
<p> </p><table width="550" border="0" align="center" cellpadding="10" 

cellspacing="0">
<tr>
  <td><p align="center">You shopping cart is empty</p>
   <p>If you find you are unable to add anything to your cart, please ensure 

that 
    your internet browser has cookies enabled and that any other security 

software 
    is not blocking your shopping session.</p></td>
</tr>
</table>
<?php
}

$shoppingReturnUrl = isset($_SESSION['shop_return_url']) ? 

$_SESSION['shop_return_url'] : 'index.php';
?>
<table width="550" border="0" align="center" cellpadding="10" 

cellspacing="0">
<tr align="center"> 
  <td><input name="btnContinue" type="button" id="btnContinue" 

value="<< Continue Shopping" onClick="window.location.href='<?php echo 

$shoppingReturnUrl; ?>';" class="box"></td>
<?php 
if ($numItem > 0) {
?>  
  <td><input name="btnCheckout" type="button" id="btnCheckout" value="Proceed 

To Checkout >>" onClick="window.location.href='checkout.php?step=1';" 

class="box"></td>
<?php
}
?>  
</tr>
</table>
<?php
require_once 'include/footer.php';
?>

and the functions used as:-

<?php
require_once 'config.php';

/*********************************************************
*                 SHOPPING CART FUNCTIONS 
*********************************************************/

function addToCart()
{
// make sure the product id exist
if (isset($_GET['p']) && (int)$_GET['p'] > 0) {
	$productId = (int)$_GET['p'];
} else {
	header('Location: index.php');
}

// does the product exist ?
$sql = "SELECT pd_id, pd_qty
        FROM tbl_product
		WHERE pd_id = $productId";

$result = dbQuery($sql);

if (dbNumRows($result) != 1) {
	// the product doesn't exist
	header('Location: cart.php');
} else {
	// how many of this product we
	// have in stock
	$row = dbFetchAssoc($result);
	$currentStock = $row['pd_qty'];

	if ($currentStock == 0) {
		// we no longer have this product in stock
		// show the error message
		setError('The product you requested is no longer in 

stock');
		header('Location: cart.php');
		exit;
	}

}		

// current session id
$sid = session_id();

// check if the product is already
// in cart table for this session
$sql = "SELECT pd_id
        FROM tbl_cart
		WHERE pd_id = $productId AND ct_session_id = '$sid'";
$result = dbQuery($sql);

if (dbNumRows($result) == 0) {
	// put the product in cart table
	$sql = "INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, 

ct_date)
			VALUES ($productId, 1, '$sid', NOW())";
	$result = dbQuery($sql);
} else {
	// update product quantity in cart table
	$sql = "UPDATE tbl_cart 
	        SET ct_qty = ct_qty + 1
			WHERE ct_session_id = '$sid' AND pd_id = 

$productId";		

	$result = dbQuery($sql);		
}	

// an extra job for us here is to remove abandoned carts.
// right now the best option is to call this function here
deleteAbandonedCart();

header('Location: ' . $_SESSION['shop_return_url']);			


}

/*
Get all item in current session
from shopping cart table
*/
function getCartContent()
{
$cartContent = array();

$sid = session_id();
$sql = "SELECT ct_id, ct.pd_id, ct_qty, pd_name, pd_price, 

pd_thumbnail, pd.cat_id
		FROM tbl_cart ct, tbl_product pd, tbl_category cat
		WHERE ct_session_id = '$sid' AND ct.pd_id = pd.pd_id 

AND cat.cat_id = pd.cat_id";

$result = dbQuery($sql);

while ($row = dbFetchAssoc($result)) {
	if ($row['pd_thumbnail']) {
		$row['pd_thumbnail'] = WEB_ROOT . 'images/product/' . 

$row['pd_thumbnail'];
	} else {
		$row['pd_thumbnail'] = WEB_ROOT . 

'images/no-image-small.png';
	}
	$cartContent[] = $row;
}

return $cartContent;
}

/*
Remove an item from the cart
*/
function deleteFromCart($cartId = 0)
{
if (!$cartId && isset($_GET['cid']) && (int)$_GET['cid'] > 0) {
	$cartId = (int)$_GET['cid'];
}

if ($cartId) {	
	$sql  = "DELETE FROM tbl_cart
			 WHERE ct_id = $cartId";

	$result = dbQuery($sql);
}

header('Location: cart.php');	
}

/*
Update item quantity in shopping cart
*/
function updateCart()
{
$cartId     = $_POST['hidCartId'];
$productId  = $_POST['hidProductId'];
$itemQty    = $_POST['txtQty'];
$numItem    = count($itemQty);
$numDeleted = 0;
$notice     = '';

for ($i = 0; $i < $numItem; $i++) {
	$newQty = (int)$itemQty[$i];
	if ($newQty < 1) {
		// remove this item from shopping cart
		deleteFromCart($cartId[$i]);	
		$numDeleted += 1;
	} else {
		// check current stock
		$sql = "SELECT pd_name, pd_qty
		        FROM tbl_product 
				WHERE pd_id = {$productId[$i]}";
		$result = dbQuery($sql);
		$row    = dbFetchAssoc($result);

		if ($newQty > $row['pd_qty']) {
			// we only have this much in stock
			$newQty = $row['pd_qty'];

			// if the customer put more than
			// we have in stock, give a notice
			if ($row['pd_qty'] > 0) {
				setError('The quantity you have 

requested is more than we currently have in stock. The number available is 

indicated in the "Quantity" box. ');
			} else {
				// the product is no longer in stock
				setError('Sorry, but the product you 

want (' . $row['pd_name'] . ') is no longer in stock');

				// remove this item from shopping 

cart
				deleteFromCart($cartId[$i]);	
				$numDeleted += 1;			


			}
		} 

		// update product quantity
		$sql = "UPDATE tbl_cart
				SET ct_qty = $newQty
				WHERE ct_id = {$cartId[$i]}";

		dbQuery($sql);
	}
}

if ($numDeleted == $numItem) {
	// if all item deleted return to the last page that
	// the customer visited before going to shopping cart
	header("Location: $returnUrl" . 

$_SESSION['shop_return_url']);
} else {
	header('Location: cart.php');	
}

exit;
}

function isCartEmpty()
{
$isEmpty = false;

$sid = session_id();
$sql = "SELECT ct_id
		FROM tbl_cart ct
		WHERE ct_session_id = '$sid'";

$result = dbQuery($sql);

if (dbNumRows($result) == 0) {
	$isEmpty = true;
}	

return $isEmpty;
}

/*
Delete all cart entries older than one day
*/
function deleteAbandonedCart()
{
$yesterday = date('Y-m-d H:i:s', mktime(0,0,0, date('m'), date('d') - 

1, date('Y')));
$sql = "DELETE FROM tbl_cart
        WHERE ct_date < '$yesterday'";
dbQuery($sql);		
}

?>

 

The Database entry is as follows:-

 

table DROP TABLE IF EXISTS `tbl_cart`;

CREATE TABLE `tbl_cart` (

  `ct_id` int(10) unsigned NOT NULL auto_increment,

  `pd_id` int(10) unsigned NOT NULL default '0',

  `ct_qty` mediumint(8) unsigned NOT NULL default '1',

  `ct_session_id` char(32) NOT NULL default '',

  `ct_date` datetime NOT NULL default '0000-00-00 00:00:00',

  PRIMARY KEY  (`ct_id`),

  KEY `pd_id` (`pd_id`),

  KEY `ct_session_id` (`ct_session_id`)

) TYPE=MyISAM AUTO_INCREMENT=58 ;

 

Link to comment
Share on other sites

Please tell us

 

1.  What you did (eg, typed data into form and clicked submit)

2.  What happened (eg, saw the message "Error in mysql query!")

3.  What you expected to happen (eg, I should have seen "Your order was submitted successfully")

Link to comment
Share on other sites

Main Program Budget.php which I wish to attach to the other 2 script.

 

Purpose of budget.php

  1> get the price which the user wish to purchase items (in form) after carrying various form of server side validation accept the price.

 

  2> show products within the price range to the customer.

 

  3> Add those product to the already existing cart are cart.php and cart_functions.php (containing all the cart functions).

 

I hope that explains it all  ;D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.