0

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 - &dollar;$pprice";
  if($postage) {
    $bodycontent .= " + P&amp;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.

4

1 回答 1

-1

你用的功能不对!!!我的意思是->mysql_fetch_array

你应该mysql_fetch_array改变mysql_fetch_assoc

看到真实的结果。

于 2012-04-24T17:14:07.363 回答