Jump to content

Shopping Cart Php Mysql


Isset1988

Recommended Posts

Hello my friends  ::) 

I tried to build a shopping cart system for my website but my knowledge stuck me.

 

Is there any simple (but reliable) php tutorial to build a shopping cart system?

 

To explain you the situation.

 

When the visitor choose a product and press the Buy button, i want to check if its id is on my database.

After that the visitor will can choose more products or delete all or update the quanties or delete one of them from basket.

I attach you my session code, but has a lot of bugs on add2cart. Maybe i add products wrong and i get wrong results from the other functions (update,delete). :/

<?php //sessions and functions to set or unset product sessions from cart
	session_start();

    If (isset($_GET["add2cart"]) && (int)$_GET["add2cart"]>0) //add product to cart with id=$add2cart 
    { 
		require_once('functions.php');
		GetMyConnection();

		$add2cart = $_GET["add2cart"];
		
	
		echo 'max'.max($_SESSION["gids"]);
		
		
		$q = mysql_query("select id from content where id='$add2cart'");
		$count=mysql_num_rows($q);
         
        If($count==1){
			if (!isset($_SESSION["gids"])) 
			{ 
				$_SESSION["gids"] = array(); 
				$_SESSION["counts"] = array(); 
			} 
			//check for current product in visitor's shopping cart content 
			$i=0; 
			while ($i<count($_SESSION["gids"]) && $_SESSION["gids"][$i] != $_GET["add2cart"]) $i++; 
			if ($i < count($_SESSION["gids"])) //increase current product's item quantity 
			{ 
				$_SESSION["counts"][$i]++; 
			} 
			else //no such product in the cart - add it 
			{ 
				$_SESSION["gids"][] = $_GET["add2cart"]; 
				$_SESSION["counts"][] = 1; 
			} 
			
		}Else{
			echo 'the product is not in our database';
		}
    }
?>
<?php
	If (isset($_GET["removeAll"])) {//remove all products from cart
		unset($_SESSION["gids"]); 
		unset($_SESSION["counts"]); 
	}
?>
<?php //remove specific product from cart
	
		if (isset($_GET["remove"]) && (int)$_GET["remove"] > 0){
			If($_GET["remove"] >0 ){
				$i = $_GET["remove"] -1;
			}Else{
				$i = $_GET["remove"];
			}
			
			unset($_SESSION["gids"]["$i"]);
		}
	
?>
<?php //update cart

    If (isset($_GET["update"]) && (int)$_GET["update"] > 0 && $_GET["q"] && (int)$_GET["q"] > 0) //remove product with productID == $remove 
    {
		$i = $_GET["update"] -1; //i decrease -1 to find the right array row
		$_SESSION["counts"][$i] = $_GET["q"]; //i update only the quantity
    }

?>
<?php //echo the cart
 //i copy that in the front page Basket.php
	$i = max($_SESSION["gids"]); //here i find max entries in this array
	$i = $i -1;
	If(isset($i) && $i>=0){
		For ($k=0;$k<=$i;$k++){
			If($_SESSION["gids"]["$k"]==0 or $_SESSION["counts"]["$k"]==0){//empty array, i dont want to echo this
			}Else{
				echo 'Session_Id: '.$_SESSION["gids"]["$k"].' Quantity: '.$_SESSION["counts"]["$k"].'<br>';
			}
		}
	}

?>


Is there any simple and reliable shopping cart tutorial?

Thank you!

Link to post
Share on other sites

What does this have to do with regular expressions?

 

 

I'd suggest using a third-party application for a shopping cart. But if you want to go through the trouble of doing it yourself, you need to learn to code using current best practices. Use PDO or at least mysqli. Don't randomly close and open PHP for no reason. Don't put variables in strings for no reason. You've got a lot to learn.

Link to post
Share on other sites

last time i looked, there were about 20,000 php cart tutorials posted in the Internet. most of the php code posted on the Internet wasn't done by professional programmers, but by php coders, that barely got their code to "work" at all, thought they had accomplished something unique, and posted it for anyone to stumble upon.

 

when creating php code, it's best if you rely on yourself and just sit down and define what you want your code and data to do, rather than to rely on code you find posted on the Internet, especially if money or personal information is involved.

 

when defining what you want code to do, you need to list what input(s) you have available, what processing you want the code to do, and what result or output you need that code to produce.

 

for an 'add to cart' block of code -

 

input: one product id from the url

 

processing:

  condition/test/validate input id - is the id present and a positive integer greater than 0?

    if(id > 0) check if id exists in products table

      if(id in table)

        if(cart doesn't exist) create empty cart

          if(id not in cart) create entry in cart with quantity 1

            else increment quantity in cart

 

result/output: cart entry for the submitted id/error messages from your code

 


 

i do have a recommendation for your cart definition, use the product id as the array index and the array value is the quantity. this will make finding/modifying information in the cart easier with less code. there's also no need for $_SESSION["counts"]. that's just redundant information.

Link to post
Share on other sites

one possible way of doing this -

<?php
session_start();
if(!isset($_SESSION["cart"])){ // create cart if it doesn't exist
    $_SESSION["cart"] = array();
}

$add2cart = isset($_GET["add2cart"]) ? (int)trim($_GET["add2cart"]) : 0; // condition input
if($add2cart > 0){ // a valid value
    $query = "select COUNT(*) from products where id=$add2cart";

    // run the query using your favorite database library functions, check for errors, and retrieve the COUNT value

    if($count==0){
        echo 'the product is not in our database'; // it is usually cleaner/clearer to handle the error condition up front in the logic
    } else {
        if(!isset($_SESSION["cart"][$add2cart])){ // check if id is not already in cart
            $_SESSION["cart"][$add2cart] = 1; // create item in cart
        } else {
            $_SESSION["cart"][$add2cart]++;    // increment item in cart
        }
    }
}

// display raw cart data for debugging purposes
echo '<pre>',print_r($_SESSION['cart'],true),'</pre>';
Link to post
Share on other sites

I'm sorry. I read again your answer carefully. I expand the session script following your logic structure.

This is what i need.  :happy-04:  I post it there if anyone want to copy this.

<?php
session_start();
if(!isset($_SESSION["cart"])){ // create cart if it doesn't exist
    $_SESSION["cart"] = array();
}

$add2cart = isset($_GET["add2cart"]) ? (int)trim($_GET["add2cart"]) : 0; // condition input
if($add2cart > 0){ // a valid value
    //$query = "select COUNT(*) from products where id=$add2cart";
    // run the query using your favorite database library functions, check for errors, and retrieve the COUNT value
    $count = 1; //i bypass this to check the sessions
    if($count==0){
        echo 'the product is not in our database'; // it is usually cleaner/clearer to handle the error condition up front in the logic
    } else {
        if(!isset($_SESSION["cart"][$add2cart])){ // check if id is not already in cart		
            $_SESSION["cart"][$add2cart] = 1; // create item in cart			
        } else {
            $_SESSION["cart"][$add2cart]++;    // increment item in cart
        }
    }
}

$remove = isset($_GET["remove"]) ? (int)trim($_GET["remove"]) : 0; // condition delete
if($remove > 0){
	unset($_SESSION["cart"][$remove]);
}

$removeAll = isset($_GET["removeAll"]); // condition delete all
if($removeAll > 0){
	unset($_SESSION["cart"]);
}

$update = isset($_GET["update"]) ? (int)trim($_GET["update"]) : 0; // condition update
$quantity = isset($_GET["quantity"]) ? (int)trim($_GET["quantity"]) : 0;
if($update > 0 && $quantity > 0){
	$_SESSION["cart"][$update] = $quantity;
}

//condition update all ?


// display raw cart data for debugging purposes
echo '<pre>',print_r($_SESSION['cart'],true),'</pre>';
?>

Now the only function i need to find is to update all the cart quantities with one click. :/

 

Thank you for your help mac_gyver!

Link to post
Share on other sites

Update all cart quantities...

I share it if someone wants to use it with the code above.

 

Front page: (i have it into a while loop. in this way i push things into an array)

<input type="text" name="<?='qty'.$key?>" value="<?=$value?>">

The session file:

//condition update all 
If(isset($_POST['update'])){
		foreach ($_POST as $key=>$value) { //first i save the post data to an array
			if (stristr($key,'qty')) { 
				$id = str_replace('qty','',$key);
				$_SESSION["cart"][$id] = $value; //save the array into my cart session
			}
		}
}
Link to post
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.