0

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:

  1. emails
  2. email_attachments

emails has the columns:

  1. sequence
  2. emailto
  3. emailfrom
  4. subject
  5. message

and *email_attachmentss* has the columns:

  1. sequence
  2. email_seq (matches sequence from the emails table)
  3. attachment

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);
}....
3
  • Use a JOIN, that's the normal way to get related data from two tables. Commented Oct 10, 2013 at 8:53
  • see my edit - thats how i usually link tables. i use JOIN sometimes but not all the time - not sure if my way above is easier? Commented Oct 10, 2013 at 8:56
  • Please be aware that the mysql_xxx() functions are deprecated and obsolete. You should consider converting your code to use the PDO library instead. Commented Oct 10, 2013 at 9:00

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.