cabey84 Posted February 28, 2010 Report Share Posted February 28, 2010 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? Quote Link to comment Share on other sites More sharing options...
falkencreative Posted March 1, 2010 Report Share Posted March 1, 2010 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; } Quote Link to comment Share on other sites More sharing options...
cabey84 Posted March 1, 2010 Author Report Share Posted March 1, 2010 Thanks so much for your help. I actually just ended up leaving out the foreach loop altogether and stuck with using an if statement within the while loop because I need to be able to loop through all the products. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.