Jump to content

Altering the Shopping Cart Tutorial to work with MySQL


cabey84

Recommended Posts

Hi,

 

I am going through the PHP Shopping Cart tutorial where xml rather than a mysql database was used to construct the data. I have been trying to adjust the code to fit with the use of the mysql database, but I keep running into some problems.

 

The first one that has me completely stumped is checking to see if the product exists in the database.

 

In the video tutorial, using xml, the code is as follows:

 

function product_exists($product_id)

{

foreach (get_xml_catalog() as $product)

{

if ($product->id == $product_id)

return true;

 

}

return false;

}

 

My code, to adjust for the use of a mysql database is as follows:

 

function product_exists($product_id)

{

global $connection;

$query = "SELECT * from products";

$result = mysql_query ($query, $connection);

$product = mysql_fetch_array($result, MYSQL_ASSOC);

foreach ($product as $item) {

if ($product_id == $product['itemName']) {

return true;

}

}

}

 

Since the mysql_fetch_array returns an associative array, I didnt think it would be so problematic to use a foreach loop as was done in the video tutorial. I think the main problem is that I am confused on how to use the foreach loop with regards to the mysql_fetch_array. Could someone please help?

Link to comment
Share on other sites

Hey Cabey84,

 

I'd actually approach this froma slightly different angle... Rather than selecting all the products and then looping through them (like you'd have to do if you were using XML), I'd suggest trying to select the specific product from the database. If that doesn't work, you know the product doesn't exist. So, for example (untested, but I believe it should work):

 

function product_exists($product_id) 
{
   global $connection;
   $query = "SELECT * from products WHERE id=$product_id";
   $result = mysql_query ($query, $connection);     
   if (mysql_num_rows($result) > 0)
   {
       return true;
   }
   return false;
}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...