My db tables look like that
First table:

Second table – lastsrvc (Last service info). id column -uniques auto-incremented id for every issue. ‘cid’ column – company’s id. It’s the link column between 2 tables: main and lastsrvc.

Now, what I want to do is, lets say, count all issues for company 1. My code sends before while 1 query and fetches all rows of main table. Then sends second query within while for every company’s row.
If in the future there will be 10 000 company’s it will load server I think. Is there any way to send 1 query instead of sending query for every company (within while)? Is it possible to use COUNT before while, instead of second query within while?
My code looks like that
<?php
$query=$db->query("SELECT * FROM main");
while($row=$query->fetch_object())
{?>
<tr>
<td><?=$row->id;?></td>
<td><?=$row->company;?></td>
<td><?=$row->address;?></td>
<td><?=$row->contact_name;?></td>
<td><?=$row->contact_phone;?></td>
<td><?php
if ($row->warr)
{
echo 'Var,'.$row->warr_year.' il';
}
else {
echo 'Yoxdur';
}
?></td>
<td>
<?php
if ($query2=$db->query("SELECT * FROM lastsrvc WHERE cid='$row->id'"))
echo $query2->num_rows;
?>
</td>
</tr>
<?php } ?>
Use this as your top-level (and only) query:
One single query with a join is almost always going to be much more efficient than running 1+n queries. You just echo out that ‘cnt’ field as usual: