I wrote a script to find all records in a collection, and tell me if the user needs to be emailed, does not need to be emailed, or has unsubscribed from email.
I can get it to tell me this information, however when adding an action as simple as echoing a test email template ($m), the scripts dies after passing over one record, resulting in error:
"Error connecting to MongoDB server the connection has been terminated, and this cursor is dead"
Code:
$date = date('Y-m-d');
$pastdate = date('Y-m-d', strtotime('-1 week'));
try {
$conn = new Mongo('localhost');
$db = $conn->remo;
$c = $db->data;
$cursor = $c->find( array('last_email'=>array('$nin' => array())));
foreach($cursor as $obj) {
if (($obj['last_email'] == null) || ($obj['last_email'] <= $pastdate)) {
if($obj['weeklyemail'] === '1') {
//Debugging
echo 'email'.$obj['email'];
//Message to send
$m = "Hello ".$obj['first_name'].", this is a test.";
echo $m;
//Do the mail
//Update the date for last_email for user
$newdate = array('$set' => array('last_email' => $date));
$cursor->update(array('email' => ''.$obj['email'].''), $newdate);
} else {
echo 'unsubscribed'.$obj['email'];
}
} else {
echo 'noemail'.$obj['email'];
}
}
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server' . $e->getMessage());
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
I am confused why the script works, until I simply add an echo. I am expecting the message ($m) to be echoed for each user that needs the email. Once I can get a simple echo to work, I plan on adding the script for the actual mailer part.