You are here:  » php sql error


php sql error

Submitted by sbedigital on Fri, 2012-01-27 20:58 in

hi dave,

i do remeber long time ago you done a mod on the forum to fix this but it no longer exist. I sometimes get database error on my random.php script which states:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /path/to/public_html/includes/database.php on line 27
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /path/to/public_html/includes/database.php on line 32

I think there is something to with this code from random.php

<?php
  if (!$config_featuredProducts) $config_featuredProducts = 8;
  $sql = "SELECT DISTINCT(merchant) AS merchant FROM `".$config_databaseTablePrefix."products`";
  $num = database_querySelect($sql,$rows);
  $merchant = $rows[rand(0,($num-1))]["merchant"];
  $sql = "SELECT name FROM `".$config_databaseTablePrefix."products` WHERE merchant='".database_safe($merchant)."' ORDER BY RAND() LIMIT ".$config_featuredProducts;
  if (database_querySelect($sql,$rows))
  {
    $sqlNames = array();
    foreach($rows as $featured)
    {
      $sqlNames[] = "'".$featured["name"]."'";
    }
    $sqlIn = implode(",",$sqlNames);
    $sql = "SELECT * , MIN( price ) AS minPrice, MAX( price ) AS maxPrice, COUNT( id ) AS numMerchants FROM `".$config_databaseTablePrefix."products` WHERE name IN (".$sqlIn.") GROUP BY name";
    database_querySelect($sql,$rows);
    $featured["products"] = $rows;
    foreach($featured["products"] as $k => $product)
    {
      if ($config_useRewrite)
      {
        $featured["products"][$k]["productHREF"] = "product/".tapestry_hyphenate($product["normalised_name"]).".html";
        $featured["products"][$k]["reviewHREF"] = "review/".tapestry_hyphenate($product["normalised_name"]).".html";
      }
      else
      {
        $featured["products"][$k]["productHREF"] = "products.php?q=".urlencode($product["normalised_name"]);
        $featured["products"][$k]["reviewHREF"] = "reviews.php?q=".urlencode($product["normalised_name"]);
      }
    }
  }
$columns = 4;
$current_column = 0;
require ("html/random.php");
?>

Could you please shed some light on this?

Noor

Submitted by support on Fri, 2012-01-27 22:09

Hello Noor,

I notice from the code above that the name field is not being made database safe so that could cause the second SQL (where the actual featured products are selected) to fail intermittently, depending on whether one (or more) product names contains non-MySQL safe characters.

To fix this, REPLACE this line (I think it will be line 12 in your random.php)

      $sqlNames[] = "'".$featured["name"]."'";

...with:

      $sqlNames[] = "'".database_safe($featured["name"])."'";

...and that should be all it is!

Cheers,
David.
--
PriceTapestry.com

Submitted by sbedigital on Fri, 2012-01-27 23:06

thanks :-)