hi, i am trying to display a random product from my database along with its description, price and image. but i am having a little trouble. i can display a random product and its info by directly inputting it into an array, but i can't call it from the database itself WITH the array.
i checked google but i just kept being sent to pages that only have scripts that do as i did below or i get taken to pages that have nothing to do with php at all.
Any help will be appreciated.
Here's the code i'm using:

<?php
	$get_pic = "SELECT car_name, LEFT(car_desc, 20), car_image FROM cars";
	$get_pic_res = mysql_query($get_pic) or die(mysql_error());
	
	if (mysql_num_rows($get_pic_res) < 1){
		$display_desc = "<p><em>No products available!</em></p>";
	}	
	else{					
		while ($pics = mysql_fetch_array($get_pic_res)){
$pics_name = strtoupper(stripslashes($pics[car_name]));
$pics_desc = stripslashes($pics[car_desc]);
$pics_price = $pics[car_price];
									
$images = array
	(
	/*array('file' => $pics_name,  // here i tried to pass the variable into the array
	'caption' => $pics_desc),*/ // i'm not sure that can be done though
	array('file' => 'mazda',
	'caption' => 'This is the Mazda 626. A cheap, yet luxurious car.'),
	array('file' => 'buick',
	'caption' => 'This car is all over the country so you may want 
	to think of getting another car.'),
	array('file' => 'hummer',
	'caption' => 'If you have the money fo this car, then you MUST have the money for fuel'),
	array('file' => 'xrc',
	'caption' => 'This is a toy car, plain and simple!')
	);
					
         $i = rand(0, count($images)-1);
	$selectedImage = "../images/{$images[$i]['file']}.jpg";
	$caption = $images[$i]['caption'];
					
	if (file_exists($selectedImage) && is_readable($selectedImage))
	{
		$imageSize = getimagesize($selectedImage);
	}
									
	}
						
}
		
?>

Dani AI

Generated

Quick summary and what went wrong: 's suggestion to pick a random row was the right direction and you were close — the description didn't appear because selecting an expression (like a substring) returns a column name that isn't car_desc unless you explicitly give it one. Also be careful to always use quoted associative keys in PHP ($row['car_desc']), not unquoted constants. Aliasing the expression in SQL or doing the truncation in PHP fixes the immediate problem.

Prefer modern, safe code and a scalable way to pick a random row. For small tables ORDER BY RAND() works, but for larger tables it gets slow. A straightforward, efficient alternative uses a row count + LIMIT/OFFSET; example (PDO + prepared statements):

<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4','user','pass',
               [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$count = (int)$pdo->query('SELECT COUNT(*) FROM cars')->fetchColumn();
if ($count > 0) {
    $offset = random_int(0, $count - 1);
    $stmt = $pdo->prepare('SELECT id, car_name, car_desc, car_image FROM cars LIMIT 1 OFFSET :o');
    $stmt->bindValue(':o', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    echo '<img src="images/'.basename($row['car_image']).'" alt="'.htmlspecialchars($row['car_name']).'">';
    echo '<p>'.htmlspecialchars(mb_substr($row['car_desc'], 0, 80)).'</p>';
}
?>

If your ID space is dense, an even faster method is to fetch MIN(id) and MAX(id), pick a random id in that range and select the first row with id >= that value (repeat if no row found). That avoids scanning/ordering the whole table.

Practical tips: stop using the old mysql_* API (use PDO or MySQLi), always escape output with htmlspecialchars, validate image filenames with basename() and check image MIME with getimagesize() or finfo, and prefer server-side truncation with mb_substr() when you need multi-byte safety. These changes make the random-image feature safer and more robust than the original snippet.

Recommended Answers

All 5 Replies

how about selecting the random records from the database itself?
if its fine then here is your req sql

$get_pic = "SELECT car_name, LEFT(car_desc, 20), car_image FROM cars ORDER BY RAND()";

this will randomize the order of records while fetching

ok i will go try it out adn i will update you in a few minutes

ok i've tried it out and it works perfectly, thanks! i just have one slight problem though, when i use SELECT car_name, [B][I]LEFT(car_desc, 20)[/I][/B], car_image FROM cars ORDER BY RAND() the description doesnt get displayed under the image, but using SELECT car_name, [B][I]car_desc[/I][/B], car_image FROM cars ORDER BY RAND() it gets displayed. any ideas? i will keep trying to figure it out though

use as

SELECT car_name, LEFT(car_desc, 20) [B]as car_desc[/B], car_image FROM cars ORDER BY RAND()

thanks a lot!!! the funny thing is that i know most the functions and their uses but i have a problem with implementation. what book(s) do(did) you use when studying php/mysql?
thanks again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.