include sql result to php mail - php

I would like to ask if what is missing in my script for sending mail, my query is fine and it shows results and I'd like to ask for help on how to include those query result into the message that I will send out. I'd really appreciate it if you could give me an advice where to start. thanks.
<?php
$cfg = array(
'display' => 'gw#mail.com',
'address' => 'support#mail.com',
'subject' => 'TEST '
. date("m/d/t h:i:s A", strtotime('TODAY')) . ' hits',
'queries' => array(
"SELECT inbox.src AS 'From Mobile Number', outbox.dst AS 'To Mobile Number', outbox.stamp AS 'Timestamp', inbox.data AS 'Message', outbox.status AS 'Status' FROM mega.outbox LEFT JOIN mega.inbox ON outbox.pid=inbox.pid WHERE outbox.sid=156 && inbox.sid=156 && stamp > NOW() - INTERVAL 3 HOUR",
),
);
include "/var/xrelay/mysql.php";
$sql = new database();
$msg = '';
foreach( $cfg['queries'] as $i ) {
$tmp = $sql->read($i, true);
if (!empty($tmp)) {
foreach($tmp[0] as $k => $v) $msg .= "$k: $v\r\n";
}
}
foreach( preg_split( '/[\s,]+/', $cfg['address'], -1, PREG_SPLIT_NO_EMPTY) as $i ) {
$sql->write("INSERT INTO mega.emails (sender,recipient,subject,message,stamp) VALUES "
. "('{$cfg['display']}','$i','{$cfg['subject']}','".$sql->escape($msg)."', NOW());");
}
?>
Is there any way to improve this more? this mailer supposed to send mail to a recipient every 3hours if there are any activity from the db. it will retrieve data last 3 hours ago and put the result as message.
include "/var/xrelay/mysql.php";
$sql = new database('sql://gateway:xrelay#00.000.000.000/test');
$cfg = array(
'display' => 'gw#mail.com',
'address' => 'g#mail.com',
'subject' => 'MAIL HITS ' . date("m/d/y h:i:s A", strtotime("NOW")) . ' hits',
);
//define('DEBUG',true);
$result = mysql_query("SELECT outbox.dst, DATE_FORMAT(outbox.stamp,'%b-%d-%Y %h:%i %p')AS 'Stamp', outbox.status FROM mega.outbox LEFT JOIN mega.inbox ON outbox.pid=inbox.pid WHERE outbox.sid=156 && inbox.sid=156 && outbox.stamp > NOW() - INTERVAL 3 HOUR");
$msg='| Mobile# | Timestamp | Status |\r\n';
while($row = mysql_fetch_assoc($result))
{
$msg .= "| ". $row['dst'] ." | ". $row['Stamp'] ." | ". $row['status'] ." |\r\n";
}
$num_rows = mysql_num_rows($result);
echo $msg;
if($num_rows != 0){
foreach( preg_split( '/[\s,]+/', $cfg['address'], -1, PREG_SPLIT_NO_EMPTY) as $i ) {
$sql->write("INSERT INTO mega.emails (sender,recipient,subject,message,stamp) VALUES " . "('{$cfg['display']}','$i','{$cfg['subject']}','". $msg ."', NOW());");
}
}
?>

Once you have the results you should create a string that you would append to the body of the e-mail. You can use sprintf for this purpose.
If you are looking for a way to send the actual e-mail, the mail function is explained here.

Related

Problem in duplication after clicking submit button multiple times

My main problem is with that code in which when I click on submit buttons many times, it inserts duplication many times in the database in which I need to avoid that. Please help me to solve this problem. These are the two tables in which I am trying to insert. mat_ans_options_choose and mat_answer.
$val = $this->input->post(null, true);
$val['id'] = $this->input->post('id');
$val['sub_type'] = $this->input->post('sub_type');
$val['timeout'] = $this->input->post('timeout');
$val['level'] = $this->input->post('level');
$val['mat_category'] = $this->input->post('mat_category');
$option = $val['option'] = $this->input->post('option');
$type = $this->input->post('type');
$marks = [];
$uid = $this->session->userdata('id');
if (isset($val['id']) && isset($option)) {
$query = $this->db->query("SELECT * FROM mat_ans_options WHERE deleted=0 AND active=1 AND question=" . $val['id']);
$result = $query->result_array();
if ($query->num_rows() > 0) {
$count1 = 1;
foreach ($result as $res) {
if ($res['marks'] == 1) {
break;
} else {
$count1++;
}
}
}
// MAT answers options choose
$query1 = $this->db->query("SELECT * FROM mat_ans_options_choose WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id']);
$result1 = $query1->result_array();
if ($query1->num_rows() > 0) {} else {
$data1 = [
'uid' => $uid,
'q' => $val['id'],
'option_chose' => $option,
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_ans_options_choose', $data1);
}
if ($count1 == $option) {
$marks = 1;
} else {
$marks = 0;
}
// if($marks==1 || $marks==0)
// {
// MAT answers
$query2 = $this->db->query("SELECT * FROM mat_answers WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id'] . " AND type=" . $type . " AND sub_type=" . $val['sub_type'] . " AND level=" . $val['level']);
$result2 = $query2->result_array();
if ($query2->num_rows() > 0) {} else {
$data = [
'uid' => $uid,
'q' => $val['id'],
'type' => $type,
'level' => $val['level'],
'sub_type' => $val['sub_type'],
'mat_category' => $val['mat_category'],
'marks' => $marks,
'timeoutstatus' => $val['timeout'],
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_answers', $data);
}
// }
return 1;
} else {
return 0;
}
Use JS in which you disable the button after first click - it will work no matter if you are using AJAX or not.
You can use JS/jQuery to limit the number of requests made on the client side. For example by disabling the button on submit:
$("#my-button").prop("disabled", true);
But if the data is sensitive for duplicates (orders, user registration etc) you should make the request limit server side with PHP. You can achieve this by adding a unique index to the tables, either on user id or on a unique token that is submitted with the html form.
Create UNIQUE index in database for uid and q. The database will not insert same question's id from same user's id mulitple times.

No success executing foreach

I wrote a following PHP+codeigniter code:
$msg = $this->db->get('Messages');
$curDate = date('Y-m-d H:i:s');
$array = array('IsRead =' => 0, 'Date <=' => $curDate);
$this->db->where($array);
$this->db->set(array('IsRead' => 1));
$this->db->update('Messages');
Which basically checks which records in Messages table meet the two conditions regarding fields IsRead and Date, and then updates only those records.
Now I would like to pick up every Date value that meets said criteria and execute some PHP code for it. I suppose it's a job that foreach directive could manage, but I have no success coding it.
Could I ask for some help.
Try following code, hope will help....
$curDate = date('Y-m-d H:i:s');
$array = array('IsRead' => 0, 'Date <=' => $curDate);
$this->db->where($array);
$this->db->set('IsRead',1));
$this->db->update('Messages');
if ($this->db->affected_rows()>0) {
echo "Update successful";
}
else
{
echo "No any row updated";
}
So, the answer seems to be:
$curDate = date('Y-m-d H:i:s');
$array = array('IsRead =' => 0, 'Date<=' => $curDate);
$this->db->where($array);
$msg = $this->db->get('Messages');
foreach ($msg->result() as $row)
{
echo $row->Date . " "; //here goes the PHP code
}
$this->db->where($array);
$this->db->set(array('IsRead' => 1));
$this->db->update('Messages');

Something not working as expected in this PHP function

I am trying to pull data from MySQL and this supposed to show complete data but this is showing only one row. This is supposed to show all rows of users. I don’t know what I did wrong:
Here is the code:
function getCashoutRequests($uid, $limit) {
if (!empty( $limit )) {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC LIMIT ' . $limit );
}
else {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC' );
}
if (mysql_num_rows( $query )) {
if ($row = mysql_fetch_object( $query )) {
$row->id;
$amount = $row->amount;
$status = $row->status;
$client_notes = nl2br( $row->user_notes );
$admin_notes = nl2br( $row->admin_notes );
$request_date = $row->request_date;
$payment_date = $row->payment_date;
$fee = $row->fee;
$priority = $hid = $row->priority;
$method = $row->method;
if ($payment_date != '0000-00-00 00:00:00') {
$payment_date = date( 'd M, Y', strtotime( $payment_date ) );
}
$request_date = date( 'd M, Y', strtotime( $request_date ) );
$payHistory []= array( 'id' => $hid, 'cash' => $amount, 'status' => $status, 'method' => $method, 'client_notes' => $client_notes, 'admin_notes' => $admin_notes, 'date' => $request_date, 'payment_date' => $payment_date, 'fee' => $fee, 'priority' => $priority );
}
return $payHistory;
}
return false;
}
On this line you have if:
if ($row = mysql_fetch_object( $query )) {
If you use if that would only go to the first value since if simply tests a condition once. Instead try while like this:
while ($row = mysql_fetch_object( $query )) {
As explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.

Populating dropdown list from database

I am trying to populate my dropdown list on a form with data from a database, i have tried the following but to no success it gives me an error saying unexpected ; i have tried removing but still getting errors?
echo form::label('myproduct', 'My Product:');
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive"); while ($row = mysql_fetch_array($sql))
{echo "<option value=\"1\">" . $row['description'] . "</option>"; }
I think i could be putting the code in the wrong place as i have two php files, one is the controller, my code below:
public function action_claimincentive() {
$this->template->content = View::factory('crm/uk/claim_incentive_form');
$this->template->content->thanks = false;
$this->template->content->val = '';
$this->template->content->post = '';
if ($this->request->post('form')) {
$post = $this->request->post('form');
$stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`User Reference`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Acknowledgement No.`, `Product`)
VALUES (:userreference, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :product)');
$stmt->param(':userreference', $post['userreference']);
$stmt->param(':claimantpostcode', $post['claimantpostcode']);
$stmt->param(':orderno', $post['orderno']);
$stmt->param(':email', $post['email']);
$stmt->param(':storename', $post['storename']);
$stmt->param(':storetown', $post['storetown']);
$stmt->param(':dateofsale', $post['dateofsale']);
$stmt->param(':dateofdelivery', $post['dateofdelivery']);
$stmt->param(':acknowledgementno', $post['acknowledgementno']);
$stmt->param(':product', $post['product']);
try {
$stmt->execute();
$this->template->content->post = $post;
$this->template->content->thanks = true;
} catch (Exception $e) {
FB::error($e);
}
}
}
And the other is the actual form, see part of it below:
echo form::label('dateofdelivery', 'Date of Delivery:');
echo form::input('form[dateofdelivery]', $val, array('class'=>'input', 'id'=>'dateofdelivery'));
echo form::label('acknowledgementno', 'Acknowledgement No:');
echo form::input('form[acknowledgementno]', $val, array('class'=>'input', 'id'=>'acknowledgementno'));
echo form::label('product', 'Product:');
echo form::select('form[product]', array(
'' => 'Please select from the list',
'In store' => 'In store',
'Word of mouth' => 'Word of mouth',
'Television' => 'Television',
'Newspaper' => 'Newspaper',
'Magazine' => 'Magazine',
'Internet' => 'Internet',
'Google Reasearch' => 'Google Reasearch',
'Radio' => 'Radio',
'Medical Recommendation' => 'Medical Recommendation',
), '', array('class="select"', 'id'=>'product'));
echo form::submit('btnSubmit', 'Submit', array('id'=>'btnSubmit', 'class'=>'button'));
echo '</div>';
echo '<div class="clearfix"></div>';
echo form::close();
You have some errors in your markup, let's see:
In this line you have some errors:
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive");
You are opening two parenthesis but only closing one should be something like:
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive"));
It's not necessary to assign the sql variable inside the method, any way I don't know which kind of framework are you using, so I am only noticing syntax errors.

Update Magento database table with a WHERE clause

I have a table called 'sample' with fields as 'sample_id, 'order_id', order_email_id', 'review_request', 'coupon_sent'.
$to_date = date('Y-m-d H:i:s',strtotime('-1 days'));
$orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('status', 'complete')->addFieldToFilter('updated_at',array('to' => $to_date ))->addAttributeToSelect('customer_email')->addAttributeToSelect('entity_id');
foreach ($orders as $order)
{
$email = $order->getCustomerEmail();
$id = $order->getEntityId();
//echo 'Email: ' . $email . ' Id: ' .$id .'<br/>' ;
$sample = Mage::getModel('sample/sample');
$sample->setOrderId($id);
$sample->setOrderEmailId($email);
$sample->save();
echo '<br/>Record Added';
}
$posts = Mage::getModel('sample/sample')->getCollection();
foreach($posts as $sample_post)
{
if($sample_post->getReviewRequest()==0)
{
code to send email to email id's from this table's order_email_id field
try
{
(if($mail->send() == true)
{
echo "<br> Mail Sent ";
//**WHERE clause condition to update 'review_request' field for all successful emails sent**
}
else {echo 'Mail not Sent';}
}
catch(Exception e) {}
So acc to my code how do I put the WHERE clause which sets review_request = 1 for all the records where the emails have been sent successfully.
Thanks in advance
Thanks #clockworkgeek for bringing that link again and downvoting which 'probed' me even further to work out the solution. :P I think I found it.
if($mail->send() == true)
{
echo "<br> Mail Sent ";
$model1 = Mage::getModel('sample/sample')->getCollection();
$model1->load()->addFieldToFilter('order_email_id',array('eq' => $toEmail))->getSelect());
foreach($model1 as $final_model)
{
$final_model->setReviewRequest(1)->save();
}
}
And this perfectly updates my table with all the records where the emails were sent with review_request = 1
Thanks.
This doesn't work for me:
$model1->load()->addFieldToFilter('order_email_id',array('eq' => $toEmail))->getSelect();
while this works:
$model1->addFieldToFilter('order_email_id',array('eq' => $toEmail))->load();

Categories