ZenCart random product block
Last modified: July 4, 2007 - 15:28
A simple code snippet to add a block with random product image and name taken from the ZenCart database.
<?php
// change these settings
$dbhost = "localhost";
$dbuser = "user";
$dbpassword = "password";
$dbname = "database"; // zencart db
$zenImageUrl = "http://www.mydomain.com/zencart/images"; //url of the zencart images directory
$zenLangCode = "1" //zencart language code (see language table)
$maxsize = "max"; // max width or height size of the image
function imageResize($width, $height, $target) {
if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}
$width = round($width * $percentage);
$height = round($height * $percentage);
return "width=\"$width\" height=\"$height\"";
}
$dbconn = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbname);
$total = "select count(products_id) as tot from products where products_status = 1 and products_image > ''";
$row = mysql_query($total);
$r = mysql_fetch_object($row);
$tot = $r->tot;
$n = rand(1, $tot);
$random_products_query = "select p.products_id, p.products_image, pd.products_name from products p left join products_description pd on p.products_id = pd.products_id where p.products_id = pd.products_id and p.products_status = 1 and pd.language_id = '$zenLangCode' and p.products_image > '' limit $n, 1";
$p = mysql_fetch_object(mysql_query($random_products_query));
$size = getimagesize("$zenImageUrl/{$p->products_image}");
?>
<div align="center">
<img <?php print imageResize($size[0], $size[1], 150) ; ?> src="<?php print $zenImageUrl."/".$p->products_image; ?>"/><br/>
<em><?php print $p->products_name; ?></em><br/><br/>
</div>