I'm writing an online shop, and I've come across an issue with a function which I'm hoping someone can help me with. The function is designed to determine if the product exists in alternate formats and link to those from the sidebar. For example, a product may exist in DVD, Blu-Ray and Digital Download.
This is my function code:
function formatExists($format, $pid) {
global $conn; global $dbname; global $loginid;
mysql_select_db($dbname, $conn);
// Get author and description of the requested product
$query = "SELECT description, author FROM products WHERE productid = $pid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$author = $row['author'];
$description = $row['description'];
}
// Find other products with the same description & author in requested format
$query = "SELECT productid FROM products WHERE format = $format AND description = '$description' AND author = '$author'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$rpid = $row['productid'];
}
if($rpid) {
return $rpid;
} else {
return 0;
}
}
I've written a loop in another part of the code, which gets all of the formats from the database, then runs the above function on them to try to find out which formats the product is available in:
$query = "SELECT formatid, description, postage FROM formats";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$id = $row['formatid'];
$desc = $row['description'];
$post = $row['postage'];
... STUFF ...
}
When '... STUFF ...' was '$bodycontent .= $id';" it echoed every format ID in the database, this is the behavior I expected. However, when I changed it to:
$pid = formatExists($id, $productid);
if($pid) {
$query = "SELECT price FROM products WHERE productid = $pid";
$result = mysql_query($query);
$pricedata = mysql_fetch_array($result, MYSQL_ASSOC);
$pprice = $pricedata['price'];
$bodycontent .= "<span>";
if($pid != $productid) {
$bodycontent .= "<a href='$siteroot/index.php?page=product&id=$pid'>";
}
$bodycontent .= "$desc - $$pprice";
if($postage) {
$bodycontent .= " + P&P";
}
if($pid != $productid) {
$bodycontent .= "</a>";
}
$bodycontent .= "</span>";
}
It stopped operating in the desired fashion, and just started returning the response for the first format ID.
If I manually change 'formatExists($id, $productid)' to 'formatExists(2, $productid)' then the price and link update, so the function is working correctly. For some reason, however, it's not running once for each category, it's just running once in my loop.
Any help will be much appreciated.
mysql_*
functions to write new code. They are no longer maintained and the community has begun deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you pick PDO, here is good tutorial. – Madara Uchiha Aug 18 '12 at 8:34mysql_*
hurts my eyes. – Madara Uchiha Aug 18 '12 at 8:35