Need help with ranking the companies by rating

Basically i have this coding that displays all companies according to each row in the companies table

if (isset($_POST['by-rank'])) {
	$search = mysqli_real_escape_string($db, $_POST['service']);
	$sql = "SELECT * FROM companies JOIN compserv ON companies.compid = compserv.compid WHERE compserv.servicename = '$search'";
	$result = mysqli_query($db, $sql);
	$queryResult = mysqli_num_rows($result);

	echo "There are ".$queryResult." results!";
	echo "<br>";
	echo "<br>";
	
	while ($row = mysqli_fetch_array($result)) {
		$compid = $row['compid'];
		$compname = $row['compname'];
		$service = $row['servicename'];
		
		// get average
		$query = "SELECT ROUND(AVG(rating),1) as averageRate, compid  FROM rank WHERE compid = '$compid'";
		$avgRes = mysqli_query($db,$query) or die(mysqli_error($db));
		$fetchRating = mysqli_fetch_array($avgRes);
		$averageRate = $fetchRating['averageRate'];
				
		if ($averageRate <= 0) {
			$averageRate = "No rating yet.";
		}

		<div class='article-box'>
			<h3><?php echo $compname; ?></h3>
			<p><?php echo $service; ?></p>
			<p>Average rating: <span id='avgrating_<?php echo $compid; ?>'><?php echo $averageRate; ?></span></p>
		</div>
		
	<?php } ?>
<?php } ?>

What i actually want was to display companies by rating in descending order (kinda like ranking). How can i do this?
I have this already:
“SELECT ROUND(AVG(rating),1) as averageRate, compid FROM rank GROUP BY compid ORDER BY avg(rating) DESC)”
How can i echo the variables in another table (company table) according to the rating that has been sorted by descending?

Really need your guys help asap thank you!

You would write a single JOIN query that gets all the related data that you want in the order that you want it. That you are already using a JOIN in the first query, you should be able to do this with a little experimenting.

Sponsor our Newsletter | Privacy Policy | Terms of Service