Generate PDF File in Account Module

Good Day, I just wanted to ask your assistance/help if anyone has any idea what is the correct way to resolve my issue right now. I want to generate a PDF File in Account modules but I also want to include the list of contacts related to it from Contact Modules.

First, this is my PDF Template Form where the list contacts will appear (note: maximum 4 contacts only base on my PDF Template)

What I did is I created an entrypoint:

$entry_point_registry['customFormLetter'] = array(
   'file' => 'custom/include/DT/EntryPoint/customFormLetter.php',
   'auth' => true
);

Then Ive just copied the formLetterPdf.php from **module/AOS_PDF_Templates** then Ive just added a custom code below to fetch the contacts records from Contact Module that are related to the Account Records:

    $q = "
    SELECT c.*
    FROM contacts c 
    LEFT JOIN accounts_contacts ac ON (c.id = ac.contact_id) AND ac.deleted = 0
    JOIN accounts a ON a.id = (ac.account_id) 
    WHERE a.id = '".$bean->id."' AND a.contact_id_c != c.id  AND a.deleted = 0
    ORDER BY c.date_entered DESC 
    LIMIT 4";

    $q = $db->query($q);

    if($db->getRowCount($q) > 0){
        $rows = $q->fetch_array();
        $i = 0;
        foreach ($rows as $row) {
            $i++;
            $printable = str_replace('${name'.$i.'}', $row['first_name']." ".$row['last_name'], $printable);
        }

    }else{
        $printable = str_replace('${name1}', 'Test No Data', $printable);
    }

But the output/result is not correct:
image

Note: I used foreach since I want to display more than 1 data from contact module.

If I don`t used foreach I can fetch one records from account module, please check below codes and resulte:
Codes:

    if($db->getRowCount($q) > 0){
        $rows = $q->fetch_array();
        $printable = str_replace('${name1}', $rows['first_name']." ".$rows['last_name'], $printable);
    }else{
        $printable = str_replace('${name1}', 'Test No Data', $printable);
    }

Result:
image

Nevermind, I was able to figure it out. But if someone is willing to help me with a better idea It would be great.

Updated Codes:

    $q = "
    SELECT c.*
    FROM contacts c 
    LEFT JOIN accounts_contacts ac ON (c.id = ac.contact_id) AND ac.deleted = 0
    JOIN accounts a ON a.id = (ac.account_id) 
    WHERE a.id = '".$bean->id."' AND a.contact_id_c != c.id  AND a.deleted = 0
    ORDER BY c.date_entered DESC 
    LIMIT 4";

    $q = $db->query($q);

    if($db->getRowCount($q) > 0){
        $results = array();
        while($rows = $q->fetch_array())
        {
            $results[] = $rows;
        }
        $i = 0;
        foreach ($results as $row) {
            $i++;
            $printable = str_replace('${name'.$i.'}', $row['first_name']." ".$row['last_name'], $printable);
        }
    }else{
        $printable = str_replace('${name1}', 'Test No Data', $printable);
    }

ADDITIONAL QUESTION:
*How to get the primary email using the Contacts ID?