Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Shopping Cart 1

Status
Not open for further replies.

LWolf

Programmer
Feb 3, 2008
77
0
0
US
I am trying to build a shopping cart into my application but all the applications I have found seem to be leaving out how the cart array works. I have found a ton of examples about product and adding, subtracting or emptying. But for someone learning php this is a little frustrating. Does anyone know a good tutorial about building a shopping cart?

Thanks.
K
 
if you are building your own, show us what you have got so far and we can help.

building carts is mostly about bullet-proofing the UI and then, later, ensuring compliance with legislation during the checkout process.

personally i would not store the cart in an array/session. i would store it in a database table and associate that with either a session key or a cookie key or a user id (if the user is logged in). the cart table would be by item, so

cartItemID,
itemID,
itemQuantity
itemUnitPrice
itemVATCode
cartID

then as you move from cart to checkout, the cart table entries becomes an order that is in a pending status; and when it is paid, the status changes to cleared and you book the data into your accounts package and your despatch package.

then you need to decide on stock handling. my preference is to deduct from stock counts at the time that items are put into the cart, but then expire the cart thirty minutes after it was last touched. and also consider business rules for price changes between putting into a cart and checking out. that's why it is worth capturing the price in the cart.


 
I thought it best to start a new topic. I found a webpage were I coppied the entire cart from his download. For right now the "cart" is more of a "list". The actual cart will be built in later.


So this code is passing 2 params: action and id. Of course it errors out during the product_id check but what confounds me is that there is no actual db check before it errors out...
<code>
$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;

}

</code>

Why does it error out before it even checks the db?
 
You may have good reason to create a shopping cart from scratch but the link you posted happens to be from a Drupal site. That may be worth investigating. Drupal offers a few options of ready-made shopping cart and commerce systems. Unless you need to learn how to do this, a ready-made system maintained by hundreds of skilled code monkeys is often the safer route (less bugs/less security holes).


And of course, there are shopping cart options for other CMS like Wordpress and Joomla.
 
Did you not include the productExists() function in your working page or did you just trim it from what you posted in the forum. That is a relevant function that cannot be excluded.
 
I know it is getting to the function, the query params are correct and the variable $product_id is correct. I can't figure out why it dies. Here is the function...

<code>
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 `idProducts` = %d;",
$product_id);
echo "SQL=" . $sql . "<br>";
return mysql_num_rows(mysql_query($sql)) > 0;
}
</code>

And why isn't the <code> tags working?
 
So I ran a test of "Select * From Products" and it still returned 0 results. What gives?
 
Does MySQL return an error on the query? Are there rows in the Products table?
 
Table and column names are case sensitive if MySQL is running on a Linux machine.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Forum code tags are posted here with brackets, not with greater/less than symbols.
 
Mr Hamilton's code looks too rough and much too simplistic to be used in production. i'd advise starting again and slowly building your own. or use a commercial product that is reputable. or use some freeware alternatives that have really good reputations and support; or take a full featured code-only version and check each line very thoroughly.

building a shopping cart is trivial in the engineering sense of the term. But getting the input specification right takes real thought about what it is you need. a UML chart can be helpful for ensuring that there are no omissions in your logic/experience tree.
 
I will eventually dress it up, look pretty and take her out. I do understand programming logic but am still very new to php. I do not want to store in the db for now b/c it is currently for viewing only. So for now if I can get the code to run I will be happy so I can get to the next problem. My first issue is not being able to get the function to return a value.

Does MySQL return an error on the query?
Only that the result is empty and dies if it is.

Are there rows in the Products table?
Yes. The result should be for idProducts value of 12

I have tried these variations of the code...
$sql = sprintf("SELECT * FROM `Products` WHERE `idProducts`=%d;",$product_id);
$sql = sprintf("SELECT * FROM `Products` WHERE `idProducts`=%d;",intval($product_id));
$sql = sprintf("SELECT * FROM Products WHERE idProducts=%d;", intval($product_id));
$sql = sprintf("SELECT * FROM Products WHERE idProducts=%d;",$product_id);

Results have been...
SQL=SELECT * FROM `Products` WHERE `idProducts`=12;
SQL=SELECT * FROM `Products` WHERE `idProducts`=12;
SQL=SELECT * FROM Products WHERE idProducts=12;
SQL=SELECT * FROM Products WHERE idProducts=12;

Also, why are the <code></code> tags not working here?

 
there are no <code> tags. on this forum we use [ignore]
Code:
...
[/ignore] tags

try this instead
Code:
function productExists($product_id) {
  /* turn on error reporting */
  $e = error_reporting(E_ALL);
  $i = ini_get('display_errors');
  ini_set('display_errors', true);

  /*   */
  $sql = sprintf("
SELECT   COUNT(*) AS cnt 
FROM     Products 
WHERE    idProducts = '%s'
", mysql_real_escape_string($product_id)); //always escape all values to be used in a query 
  $result = mysql_query($sql);
  if(!$result) die(mysql_error()); //error checking
  $row = mysql_fetch_object($result);
  if(!$row) die(mysql_error()); //error checking

  /* reset error reporting */
  error_reporting($e);
  ini_set('display_errors', $i);
  /* */
  return $row->cnt > 0;
}
 
My connection string is pdo...would that be causing the error msg..."No database selected"?
 
How are you selecting the database?

Are you specifying it when you create the connection?

ie.
Code:
$dsn = 'mysql:[b]dbname=mydbname[/b];host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
for pdo

Code:
function productExists($product_id) {
  global $pdo;
  /* turn on error reporting */
  $e = error_reporting(E_ALL);
  $i = ini_get('display_errors');
  ini_set('display_errors', true);

  /*   */
  $sql = "
SELECT   COUNT(*) AS cnt 
FROM     Products 
WHERE    idProducts = ?
";
  $s = $pdo->prepare($sql);
  if($s == false):
    print_r($pdo->errorInfo());
  endif;
  $result = $s->execute(array($product_id));
  if(!$result):
    print_r($s->errorInfo());
  endif;
  $row = $s->fetchObject();
  /* reset error reporting */
  error_reporting($e);
  ini_set('display_errors', $i);
  /* */
  return $row->cnt > 0;
}
 
Ok, it is returning from the function but not displaying because it is not coming up with a recordcount outside the function. Do I need to create a mysql connection if that is the code being used? So I created (I think) a mysql connection with...
Code:
$mysql=mysqli_connect("myhost.com","myuser","mypassword","mydatabase");

Here is the revised basic code from Mr Hamilton's cart...
Code:
foreach($_SESSION['cart'] as $product_id => $quantity) {	
    $sql = sprintf("SELECT Vendor, Product, Aisle, Bay, Price FROM Products WHERE idProducts = %d;", $product_id); 
    $result = mysql_query($sql);
					
    //Only display the row if there is a product (though there should always be as we have already checked)
    if(mysql_num_rows($result) > 0) {
    
    echo $sql . "!!!<br>"; /////THIS IS THE TEST LINE TO SEE IF IT GETS TO THIS POINT FOR DISPLAY/////
    
    list($Vendor, $Product, $Price) = mysql_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 <a href=\"$_SERVER[PHP_SELF]?action=remove&id=$product_id\">X</a></td>";
    echo "<td align=\"center\">$line_cost</td>";
					
    echo "</tr>";				}
 
Do I need to create a mysql connection if that is the code being used?
Yes.

You can't mix and match db libraries.

If you use PDO you need PDO methods. if you use mysql[red]i[/red] you need msyql[red]i[/red] methods. If you want to sue mysql methods then you need a mysql connection not a PDO or mysql[red]i[/red] connection.

You should be getting notices about this. things like:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
So I have mysql connection set above the header...
Code:
$mysql=mysqli_connect("myhost.com","myuser","mypassword","mydatabase");

I am using pdo in the function which returns a value because it gets to the code in the if statement...
Code:
function productExists($product_id) {

I believe the problem is with this line because everything else prints (the table plus test lines to see where the execution gets to)...
Code:
list($Vendor, $Product, $Price) = mysql_fetch_row($result);

The code is still the same as above although I cannot figure out why it will not print out $Vendor, $Product, $Price



 
Why are you using pdo and mysql* connection and functions in the same script? Why not use one or the other?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top