I’ve reformatted your code to make it cleaner to see what it is doing.
Where is the query for this loop?
while($row4 = sqlsrv_fetch_array($result))
{
$form = $row4['Form_Id'];
$html .= '<tr>';
$html .= '<td>' . $form . '</td>';
$html .= '</tr>';
}
This can be cleaned, I just don’t have enough information on the data model. A summary guess, something along these lines,
SELECT DISTINCT
form_id
, COUNT(case when item_status = 'COMPLETE' then 1 END) OVER(PARTITION BY item_id) as total_complete
,COUNT(item_id) OVER(PARTITION BY item_id) as total_item
FROM detailitem
This will give you a complete working record set. However, if you are just after the completed = total, that should be specified in the where clause and you will only iterate over those, making the performance improve drastically depending on your table size.