Reputation: 2022
Yes I read the documentation, but sometimes I also need help from something that doesn't come from a book.
I'm trying to write a script that sends an email to all users within the database whenever the admin posts a new blog entry. Here is my code so far:
public function actionCreate()
{
$model=new TbPost;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['TbPost']))
{
$model->attributes=$_POST['TbPost'];
$this->emailAll();
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
//email all Function
public function emailAll()
{
//assuming that id is from the email table(unless email is under a members table)
$sql = mysql_query("select email from tb_user");
while ($row = mysql_fetch_assoc($sql)) {
$to = $row['emailAdd'];
$subject = 'NEW UPDATE FROM ADMIN';
$message = 'HELLO TEST';
$headers = 'From: [email protected]' . "\r\n";
$headers .= 'BCC: ' . implode(', ', $to) . "\r\n";
mail($to, $subject, $message, $headers);
}
}
the first function "actionCreate" is yiis generated function and I added "$this->emailAll();" to call the function I created to email all users whenever there is a new create.
Problem is, I know that the sql won't work because yii has its own way of connecting to the database and I'm not sure how I would do that.
Upvotes: 0
Views: 97
Reputation: 6296
In my response, I am assuming you have a model for users as well. If you don't, then you should create one.
Your query can be converted to the Yii form like this
$rsltAllmails = User::model()->findAll();
This should an array of objects, each one representing a single row of the query results. You can process them as follows :
foreach ($rsltAllmails as $recEmail) {
$to = $recEmail->emailAdd;
// ...
// ...and others ...
// ...
}
Upvotes: 0
Reputation: 5955
Here's the part of the documentation you are looking for: http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder#building-data-retrieval-queries
Also, a suggestion. It generally is easier to test your logic in the future if it isn't embedded in controllers.
Probably worth moving your code out of your controller. There are a few places you could out it, but I would suggest creating a CActiveRecordBehavior, watching the afterSave event and sending out an email (including a link to the post?) after your post model has saved.
Upvotes: 1