Send email to adress from mysql database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
poop5565
Forum Newbie
Posts: 1
Joined: Tue Mar 08, 2011 8:37 am

Send email to adress from mysql database

Post by poop5565 »

I would like to be able to send emails to people who have entered their details in my sql database.
I have some code that I think should work, but no such luck.
The database name is correct, the table name is LtUsers, and email is stored in the Email field. All I need to happen is for the code to connect to the database, select the email addresses and send the same static text email to all of them.

I have pasted the code below. When I run it, there are no error messages - just a blank screen and the emails are not sent. I know I am missing something obvious here - but any help would be great.

<?php // set db access info as constants
define ('DB_USER','mydbuser');
define ('DB_PASSWORD','mypass');
define ('DB_HOST','localhost');
define ('DB_NAME','mydbname');

// make connection and select db
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
mysql_select_db(DB_NAME) OR die ('Could not select the db: ' . mysql_error() );

$recipients = "SELECT Email FROM LtUsers";
$email_list = $db->query($recipients);
foreach($email_list as $row) { $to = $row['email'];
$subject = "Subject test subject";
$body = "Message from me to all";
if (mail($to, $subject, $body)) { echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
}
?>
User avatar
Kadanis
Forum Contributor
Posts: 180
Joined: Tue Jun 20, 2006 8:55 am
Location: Dorset, UK
Contact:

Re: Send email to adress from mysql database

Post by Kadanis »

For starters you are mixing your variable names up. Starting with $dbc for the connection, then using $db later on.

Secondly you seem to be trying to use both mysql and mysqli functions. You need to pick one or the other and stick to it.

Exampe using mysql (which you started with your mysql_connect function). Obviously you'll need to fix this up as I've used junk text for the variables

Code: Select all

$dbc = mysql_connection('host', 'user', 'pass');

mysql_select_db('dbname');

$result = mysql_query('your query here');

foreach ($row = mysql_fetch_assoc($result)) {
    $to = $row['email'];

    //--- snip ---//

    echo $to; //or do something else with the data
}

PS in future try to put your code in the code block tags, it makes it much easier to read when posting.
Post Reply