Update Magento database table with a WHERE clause - php

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();

Related

Bronto PHP API to get subscription status to a specific list for a specific email

I am trying to figure out how to using PHP and the Bronto API to identify if a user is subscribed or unsubscribed to a specific email list.
I am using the below code and my issue is that regardless if the user is subscribed or unsubscribed I always get a status of "active" for the user and what I need to see is not if they are on the list but unsubscribed or on the list and subscribed.
Anyway know what I should change?
<?php
$client = new SoapClient('https://api.bronto.com/v4?wsdl', array('trace' => 1,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS));
try {
//token
$token = "abc 123 and yz";
//print "logging in\n";
$sessionId = $client->login(array('apiToken' => $token))->return;
$session_header = new SoapHeader("http://api.bronto.com/v4",
'sessionHeader',
array('sessionId' => $sessionId));
$client->__setSoapHeaders(array($session_header));
// set up a filter to read contacts and match on email address
$filter = array('email' => array(array('operator' => 'EqualTo',
'value' => 'fake.person#gmail.com'
),
),
);
$contacts = $client->readContacts(array('pageNumber' => 1,
'includeLists' => false,
'filter' => $filter,
)
)->return;
// print matching contact email addresses
foreach ($contacts as $contact) {
//$contact->status always seems to have a status of active or null ??
if($contact->status ='subscribed')
{
echo " <a href='' class='btn btn-primary'>Unsubscribe</a>";
}
else if($contact->status ='Unsubscribed')
{
echo " <a href=''>Subscribe</a>";
}
//print $contact->email . ': ' . $contact->status . "\n";
}
} catch (Exception $e) {
print "uncaught exception\n";
print_r($e);
}
I think you are misusing the object property "status". If you look at this page, https://help.bronto.com/bmp/reference/r_api_soap_contactfilter.html, it shows all the the things status equals to.
To be honest I think it would be better to use this the filter function to select the unsubscribed users and perform logic based on results of the filter.What does $contact->status == "unsub" return?
I mean there is always this https://help.bronto.com/bmp/reference/r_api_soap_readunsubscribes.html method for selecting unsubscribed users and then perform logic on users not found in this group.
// print matching contact email addresses
foreach ($contacts as $contact) {
//$contact->status always seems to have a status of active or null ??
if($contact->status != 'unsub')
{
echo " <a href='' class='btn btn-primary'>Unsubscribe</a>";
}
else if($contact->status =='unsub')
{
echo " <a href=''>Subscribe</a>";
}
//print $contact->email . ': ' . $contact->status . "\n";
}
I just noticed that your operators are not right. you have "=", shouldn't it be "=="?

phpscript stops after 4th sleep

I have a csv file containing about 3500 user's data. I want to import these users to my database and send them an email that they are registered.
I have the following code:
public function importUsers()
{
$this->load->model('perk/engagement_model');
$this->load->model('user/users_model');
$this->load->model('acl/aclUserRoles_model');
$allengagements = $this->engagement_model->getAll();
$filename = base_url() . 'assets/overdracht_users.csv';
$file = fopen($filename, "r");
$count = 0;
$totalImported = 0;
$importFails = array();
$mailFails = array();
while (($mappedData = fgetcsv($file, 10000, ";")) !== FALSE)
{
$count++;
//Skip first line because it is the header
if ($count > 1) {
if (!empty($mappedData[0])) {
$email = $mappedData[0];
$user = $this->users_model->getByEmail($email);
if (!$user) {
$user = new stdClass();
$user->email = $mappedData[0];
$user->first_name = $mappedData[1];
$user->family_name = $mappedData[2];
$user->address_line1 = $mappedData[3];
$user->address_postal_code = $mappedData[4];
$user->address_city = $mappedData[5];
$user->address_country = 'BE';
$user->volunteer_location = $mappedData[5];
$user->volunteer_location_max_distance = 50;
$user->phone = $mappedData[6];
if (!empty($mappedData[7])) {
$user->birthdate = $mappedData[7] . "-01-01 00:00:00";
} else {
$user->birthdate = null;
}
foreach ($allengagements as $eng) {
if ($eng->description == $mappedData[8]) {
$engagement = $eng->engagement_id;
}
}
$user->engagement = $engagement;
if (!empty($mappedData[9])) {
$date_created = str_replace('/', '-', $mappedData[9]);
$date_created = date('Y-m-d H:i:s', strtotime($date_created));
} else {
$date_created = date('Y-m-d H:i:s');
}
$user->created_at = $date_created;
if (!empty($mappedData[10])) {
$date_login = str_replace('/', '-', $mappedData[10]);
$date_login = date('Y-m-d H:i:s', strtotime($date_login));
} else {
$date_login = null;
}
$user->last_login = $date_login;
$user->auth_level = 1;
$user->is_profile_public = 1;
$user->is_account_active = 1;
$combinedname = $mappedData[1] . $mappedData[2];
$username = str_replace(' ', '', $combinedname);
if (!$this->users_model->isUsernameExists($username)) {
$uniqueUsername = $username;
} else {
$counter = 1;
while ($this->users_model->isUsernameExists($username . $counter)) {
$counter++;
}
$uniqueUsername = $username . $counter;
}
$user->username = $uniqueUsername;
$userid = $this->users_model->add($user);
if (!empty($userid)) {
$totalImported++;
//Add the user in the volunteer group in ACL
$aclData = [
'userID' => $userid,
'roleID' => 1,
'addDate' => date('Y-m-d H:i:s')
];
$this->aclUserRoles_model->add($aclData);
//Registration mail to volunteer
$mail_data['name'] = $user->first_name . ' ' . $user->family_name;
$mail_data['username'] = $user->username;
$this->email->from(GENERAL_MAIL, 'Test');
$this->email->to($user->email);
//$this->email->bcc(GENERAL_MAIL);
$this->email->subject('Test');
$message = $this->load->view('mail/register/registration',$mail_data,TRUE);
$this->email->message($message);
$mailsent = $this->email->send();
if (!$mailsent) {
array_push($mailFails, $mappedData);
}
} else {
array_push($importFails, $mappedData);
}
if ($count % 50 == 0) {
var_dump("count is " . $count);
var_dump("we are sleeping");
$min=20;
$max=40;
$randSleep = rand($min,$max);
sleep($randSleep);
var_dump("end of sleep (which is " . $randSleep . "seconds long)");
}
var_dump($user);
} else {
array_push($importFails, $mappedData);
}
}
}
}
var_dump("Totale aantal rijen in het bestand (met header) : " . $count);
var_dump("Totale aantal geimporteerd in de database : " . $totalImported);
var_dump("Totale aantal gefaalde imports in de database : " . count($importFails));
var_dump("Deze zijn gefailed : ");
var_dump($importFails);
}
If I do not add the users in the database, or send out a mail, and just var_dump() the $user, i can see all 3500+ users being correctly created in php objects (so they should be able to be inserted correctly).
The problem is that I want to add in a random sleep, between 20 and 40 seconds after every 50 mails that I sent.
So I started doing some testing and after commenting out the insert and mail code, I started running the script, noticing that after some amount (not 50 at all), it just stops for a bit, then continues and shows me the the var_dumps in my if case at the bottom, it can be shown here in the screenshots below.
The first screenshot shows the code stopping for a bit (note that I am only var_dumping stuff, i am not adding something in the database or sending out an email yet).
This screenshot shows what happens after the script reaches 200:
The script just completely stops from this point on. I have tried this 3 times, and every single time it stops exactly on 200.
What is happening here??
Most likely you're hitting default PHP limits. temporarily remove PHP default limits with:
ini_set('memory_limit',-1);
set_time_limit(0);
then, rerun the script and check your output.
There can be multiple reasons, but to know the exact one please enable error output with.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
and if limits are not the problem, the errors will tell you more.
HINT: using logs are still better than outputting errors to the visitors, but my guess is you're testing this on your computer.

How to compare data from two tables

I have two database (mysql) with the same structure. I want to:
compare data in two table. Table one - home and the second work,
send email with results,
update data in table work.
My query:
select id, code, quantity from wpx_products
I run this query in table home and work (two databases). And this is output:
"3";"home 005-07";"2"
"63";"home 033-12";"2"
"15";"home 005-19";"2"
and from work:
"1";"work 005-07";"2"
"2";"work 033-12";"5"
"3";"work 005-19";"2"
What I want to do ? What I mean by "compare" ? I want find record with excluding tag work or home in column 'code'. For example I want to find 033-12 and check quantity. If the difference copy value from home to work.
In first second I want to use trigger in mysql. But this is not solution for me because I cant run it by myself and I can't send email with results. What is the best way to achieve this functionality ? Thanks for help.
Kind regards
---------------------edit----------------------------
I check this code below (thanks #AntG). And I have one problem. When I print
foreach ($result_target AS $target) {
$code_target = substr($target['code'], 4);
if ($code_source === $code_target) {
if ($source['quantity'] !== $target['quantity']) {
print $source['quantity'] .' -> ' . $target['quantity']."<br /><br />";
$match[] = array('code' => $source['code'], 'quantity' => $source['quantity'], 'targetid' => $target['id'], 'sourceid' => $source['id']);
}
$found = true;
break;
}
}
I have this results: http://suszek.info/projekt1/ Like You see there is 50 values. When I print $match there is much more, duplicated value and I don't know why ?
$msg = '';
foreach ($match AS $entry) {
$msg .= 'Change identified: Home_ID=' . $entry['sourceid'] . ' code: ' . $entry['code'] . ' quantity:' . $entry['quantity'] . PHP_EOL . '<br />';
print $msg;
/* Perform DB updates using $entry['targetid'] and $entry['quantity'] */
}
I have this results: http://suszek.info/projekt1/index_1.php And all code:
$match = array(); $new = array();
foreach ($result_source AS $source) {
$found = false;
$code_source = substr($source['code'], 4);
foreach ($result_target AS $target) {
$code_target = substr($target['code'], 4);
if ($code_source === $code_target) {
if ($source['quantity'] !== $target['quantity']) {
print $source['quantity'] .' -> ' . $target['quantity']."<br /><br />";
$match[] = array('code' => $source['code'], 'quantity' => $source['quantity'], 'targetid' => $target['id'], 'sourceid' => $source['id']);
}
$found = true;
break;
}
}
if (!$found) {
$new[] = array('code' => $source['code'], 'quantity' => $source['quantity'], 'sourceid' => $source['id']);
} } $msg = ''; foreach ($match AS $entry) {
$msg .= 'Change identified: Home_ID=' . $entry['sourceid'] . ' code: ' . $entry['code'] . ' quantity:' . $entry['quantity'] . PHP_EOL
. '<br />';
print $msg;
/* Perform DB updates using $entry['targetid'] and $entry['quantity'] */ }
foreach ($new AS $entry) {
$msg .= 'New Entry: Home_ID=' . $entry['sourceid'] . ' code: ' . $entry['code'] . ' quantity:' . $entry['quantity'] . PHP_EOL . '<br
/>';
#print $msg;
/* Perform DB inserts using $entry['code'] and $entry['quantity'] if this is desired behaviour */ }
/* Send email with $msg */
If you are capturing both query results in a $results array, then I think substr() is the PHP function that you are after here:
$match=array();
$new=array();
foreach($results_home AS $home)
{
$found=false;
$code=substr($home['code'],5);
foreach($results_work AS $work)
{
if($code===substr($work,5))
{
if($home['quantity']!==$work['quantity'])
{
$match[]=array('code'=>$home['code'],'quantity'=>$home['quantity'],'workid'=>$work['id'],'homeid'=>$home['id']);
}
$found=true;
break;
}
}
if(!$found)
{
$new[]=array('code'=>$home['code'],'quantity'=>$home['quantity'],'homeid'=>$home['id']);
}
}
$msg='';
foreach($match AS $entry)
{
$msg.='Change identified: Home_ID='.$entry['homeid'].' code: '.$entry['code'].' quantity:'.$entry['quantity'].PHP_EOL;
/* Perform DB updates using $entry['workid'] and $entry['quantity'] */
}
foreach($new AS $entry)
{
$msg.='New Entry: Home_ID='.$entry['homeid'].' code: '.$entry['code'].' quantity:'.$entry['quantity'].PHP_EOL;
/* Perform DB inserts using $entry['code'] and $entry['quantity'] if this is desired behaviour */
}
/* Send email with $msg */

PDO Update 1 column multiple rows with array

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

ADOdb and null fields

I'm using the last version of ADOdb PHP (5.18) to make some queries in a SQL Server database.
I select data in this way:
$rS = $localDb->Execute($sql);
if (!$rS) {
echo "Error: " . $localDb->ErrorMsg() . "\n";
}
else {
$tot = $rS->RecordCount();
echo " " . $tot . " record da inserire...\n";
while (!$rS->EOF) {
$id = $rS->fields['id'];
$field1 = $rS->fields['field1'];
$field2 = $rS->fields['field2'];
$rS->MoveNext();
}
}
All works, and I fetch data, but when a field in the database's current row is NULL, the relative element in $rS->fields has the value of the value of the last not-NULL row for the same field.
This is a big problem because I don't have correct data in the current row.
I tried search for this problem but I did not find any solution.
Coud you help me, please?
Look into adodb5/adodb.inc.php and find the GetRowAssoc function. It should be the following defintion:
function GetRowAssoc($upper=ADODB_ASSOC_CASE_UPPER)
{
$record = array();
if (!$this->bind) {
$this->GetAssocKeys($upper);
}
foreach($this->bind as $k => $v) {
if( array_key_exists( $v, $this->fields ) ) {
$record[$k] = $this->fields[$v];
} elseif( array_key_exists( $k, $this->fields ) ) {
$record[$k] = $this->fields[$k];
} else {
# This should not happen... trigger error ?
$record[$k] = null;
}
}
return $record;
}

Categories