Page 1 of 1

Send email to adress from mysql database

Posted: Tue Mar 08, 2011 8:57 am
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>");
}
}
?>

Re: Send email to adress from mysql database

Posted: Tue Mar 08, 2011 9:10 am
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.