Skip to main content
Max Resnikoff
Participating Frequently
October 7, 2015
Answered

How to get emails from 2 MySQL tables

  • October 7, 2015
  • 1 reply
  • 738 views

Hi,

I need to use only 1 query to get all emails which are stored in two different tables.

This then goes on to create an array and gets imploded for emailing, and another variable explodes it for displaying as a list on the page.

Here is the query which gets the emails from 1 table, but is missing the statements to get the emails from the other table (named: clients)

<?php

//Get users emails//

$user_sql = "SELECT * FROM users GROUP BY email";

$user_query = $con->query($user_sql);

//$user_row = $user_query->fetch_array();

//implode//

$user_emails = array();

while($user_row = $user_query->fetch_array()) 

{

    $user_emails[]=$user_row["email"];

}

//Set variables//

$email_recipients = implode(", ", $user_emails);

$user_recipients = explode(',', $email_recipients);

?>

Thanks!

This topic has been closed for replies.
Correct answer Rob Hecker2

$user_sql = "SELECT email FROM users UNION SELECT email FROM prod_book";

1 reply

Rob Hecker2
Legend
October 7, 2015

Use mySQL UNION to include two separate queries into one, which can be sorted.

The key to using UNION is the the same columns must be returned from each table. If the column names are not the same, us an alias. See example below:

SELECT email, name, address FROM

(SELECT email, name, address FROM students WHERE student_age > 18)A

UNION

(SELECT staff_email AS email, staff_name AS name, address FROM staff)

ORDER BY name

Max Resnikoff
Participating Frequently
October 7, 2015

I have changed it to this:

<?php

//Get users emails//

$user_sql = "SELECT email FROM users UNION email FROM prod_book";

$user_query = $con->query($user_sql);

//$user_row = $user_query->fetch_array();

//implode//

$user_emails = array();

while($user_row = $user_query->fetch_array())

{

    $user_emails[]=$user_row["email"];

}

//Set variables//

$email_recipients = implode(", ", $user_emails);

$user_recipients = explode(',', $email_recipients);

?>

But I am getting an error on page load:

Fatal error: Call to a member function fetch_array() on a non-object in /home4/mresnik/public_html/admin/newsletter_general_dispatch.php on line 76

Rob Hecker2
Rob Hecker2Correct answer
Legend
October 7, 2015

$user_sql = "SELECT email FROM users UNION SELECT email FROM prod_book";