Reputation: 3225
I have an email function that looks like:
function send_email_with_attachment($to, $from, $email_att, $subject, $body)
I have 2 tables that this function gets its data from to send emails:
emails has the columns:
and *email_attachmentss* has the columns:
So i want to be able to select a row from the emails table and then select all the related rows in the *email_attachments* table and send all the attachments in one email
whats the best way to do this?
I usually do things like:
$sql="SELECT * from table1 where col = 'condition' ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs))
{
$sql2="SELECT * from table2 where table1_col = '".$result["col"]."' ";
$rs2=mysql_query($sql2,$conn);
$result2=mysql_fetch_array($rs2);
}....
Upvotes: 0
Views: 90
Reputation: 780688
Use the following outer join:
SELECT e.sequence, e.emailto, e.emailfrom, e.subject, e.message, a.attachment
FROM emails e
LEFT JOIN email_attachments a ON a.email_seq = e.sequence
ORDER by e.sequence
Then loop over the rows from this. When the sequence is the same as the previous row, push the attachment onto an array of attachments (unless it's NULL, which will occur if there are no attachments associated with the email).
Upvotes: 1
Reputation: 11830
Write a join query and then create an array and use foreach loop. Your join query should be something like this
"select e.email,e.sequence,e.emailto,e.emailfrom,e.subject,e.message,ea.email_seq, ea.attachment from email e join email_attachments ea on ea.email_seq = e.sequence;
Upvotes: 1