Mandrill appears to be breaking a MySQL Select - php

I have stripped this right down, to try and find the source of this issue, but can not pin point it at all.
This successfully echos each of the IDs
$result = mysqli_query($con,"SELECT id FROM users");
// Each user matching criteria
while($row = mysqli_fetch_array($result))
{
echo $row['id'];
}
However when I include Mandrill it stops working, however I will still get the first ID echo'd
// Search Database for users who signed up yesterday
$result = mysqli_query($con,"SELECT id FROM users");
// Each user matching criteria
while($row = mysqli_fetch_array($result))
{
echo $row['id'];
include($_SERVER['DOCUMENT_ROOT'].'/src/Mandrill.php');
$mandrill = new Mandrill('hidden');
try {
$template_name = $content_template;
$message = array(
'html' => '<p>Example HTML content</p>',
'text' => 'Example text content',
'subject' => 'test',
'from_email' => 'hidden',
'from_name' => 'hidden',
'to' => array(
array(
'email' => 'hidden',
'name' => 'Tim',
'type' => 'to'
)
),
'headers' => array('Reply-To' => 'hidden.com'),
'important' => false,
'track_opens' => true,
'track_clicks' => true,
'tags' => array('$meta_tags'),
'google_analytics_domains' => array('hidden'),
'metadata' => array('website' => 'hidden')
);
$ip_pool = 'Main Pool';
$result = $mandrill->messages->sendTemplate('jotText-Auto-i101-welcome', $template_content, $message, $async, $ip_pool, $send_at);
print_r($result);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
}
The error message I get is
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given in /home/timbaker/public_html/jottext/foundation/database_tasks/cron_welcome.php on line 18
Which suggests to me it is a problem with the original query... But I can't work out why Mandrill causes this to happen?
Also worth noting:
- No error messages from Mandril
- Email does successfully send

Initially, $result variable stored only the result of mysqli_query invocation, and it worked quite fine. But when you've added the mail-sending code, you accidentally reused the same variable for storing the result of Mandrill action:
$result = $mandrill->messages->sendTemplate(...);
...thus losing its initial value (of mysqli_result), and swapping it (a resource) with a new value (an array) - hence the error message you got.
Apparently, the easiest way out of this is renaming this variable:
$mailStatus = $mandrill->messages->sendTemplate(...);
print_r($mailStatus); // or do something else with it
The bottom line: try to avoid too generic names - eventually all $vars and $data and $result will bite you quite hard when you mix them. And I'm not even talking about readability here. )
As a sidenote (kudos to #Pierre for mentioning that), you'd better move instantiating of $mandrill variable outside of the loop - otherwise you'll have include working each time a new row is processed.

Related

How to get collection class object from mongodb/driver/manager in PHP

I am using the (current? not sure, php documentation is very opaque to me) method to connect to a MongoDB from PHP:
$manager = new MongoDB\Driver\Manager("mongodb://{$user}:{$pwd}#{$url}", array("ssl" => true), array("context" => $ctx));
From there, if I want to write something I do the following:
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
$filter,
['$set' => $value],
['multi' => false, 'upsert' => $upsert]
);
$results = $manager->executeBulkWrite("$DB.$collection", $bulk);
var_dump($results);
All the documentation on the MongoDB PHP tutorials starts with a $collection object... and the functions thereafter seem much more user-friendly (getInsertedID... insertOne...find...findOne...etc).
For example:
<?php
$collection = (new MongoDB\Client)->test->users;
$insertManyResult = $collection->insertMany([
[
'username' => 'admin',
'email' => 'admin#example.com',
'name' => 'Admin User',
],
[
'username' => 'test',
'email' => 'test#example.com',
'name' => 'Test User',
],
]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());
It is not clear to me, how they are actually connecting to the DB... how would I go from the $manager connection to a $collection?
On the MongoDB PHP documentation page, it says 'You can construct collections directly using the driver’s MongoDB\Driver\Manager class'. Unfortunately, a search on the resulting page doesn't include the word 'collection' other than as a side comment in a user contributed note'
Elsewhere on the MongoDB PHP reference pages, I see nowhere that the MongoDB\Manager class is described.
So, how do I get access to the many features in the MongoDB\Collection class?
I was not able to get a collection out of the Manager class, however, I was able to use the bulkWrite class to execute an insert in a secure fashion (I believe). I expect the same pattern will work for reads and updates as well.
Code snippet for those that come here after me:
//echo "Specify the cert...";
$SSL_DIR = ".";
$SSL_FILE = "XXXXXX.pem";
$ctx = stream_context_create(array(
"ssl" => array(
"cafile" => $SSL_DIR . "/" . $SSL_FILE,
))
);
//echo "Done\n";
// echo "Creating manager...";
$manager = new MongoDB\Driver\Manager("mongodb://{$user}:{$pwd}#{$url}", array("ssl" => true), array("context" => $ctx));
// echo "Done!\n";
// echo "Making BSON...";
$bson = MongoDB\BSON\fromJSON($newData);
// echo "Done!\nMaking Value...";
$value = MongoDB\BSON\toPHP($bson);
$value->_id = (string) new MongoDB\BSON\ObjectID;
// echo "Done!\nMaking Bulk...";
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert($value);
// echo "Done!\nExecuting Bulk Write";
$results = $manager->executeBulkWrite("$db.$collection", $bulk);
if($results->getInsertedCount()==1) {
echo $value->_id;
} else {
echo $results->getWriteErrors();
}
// echo "Done!\n";

Google Spreadsheet API and Codeigniter

I have a form, it has 4 data..
Right now I got the data on $_POST. And I want to put it to Google Spreadsheet using their API.. But i'm too newbie to understand the code..
I just only achived put Google Client API to codeigniter, but I don't know how to use it.
My code is look like this..
$this->load->library('google');
$values = array(
array(
$this->input->post('name'),
$this->input->post('email'),
$this->input->post('reason'),
$this->input->post('mobile'),
date('Y-m-d')
)
);
$body = new Google_Service_Sheets_ValueRange(array(
'values' => $values
));
// $params = array(
// 'valueInputOption' => $valueInputOption
// );
$result = $this->google->spreadsheets_values->update("1gg8rHsKM3DhMaJVY-YexQyggAoq1pUCB5LpP5NFah8A", "Sheet1!A2:E2", $body, "");
I don't know what the param is intended for, so I leave it blank..
I run this code and get error Message: Undefined property: Google::$spreadsheets_values
You're missing a few things, let's go step by step.
Firstly, you need to authenticate (seems like you've done it already):
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
Specify how are you sending the data:
$valueInputOption = 'RAW';
Creating the array (note that 0 is column one, 1 is column 2 and 2 is column 3). If you want to send multiple lines just do like the example bellow or if it's just one line take the [$i] and just do $values = array(...);:
$valuesb[$i] = array(
0 => "Value 1",
1 => "Value 2",
2 => "Value 3"
);
Please note that you need to specify the spreadsheet range and tab name:
$data[] = new Google_Service_Sheets_ValueRange(
array(
'range' => '\'TAB NAME HERE\'!A2:AU10000',
'values' => $valuesb
)
);
Then finally sending the data
$requestBody = new Google_Service_Sheets_BatchUpdateValuesRequest();
$requestBody->setValueInputOption($valueInputOption);
$requestBody->setData($data);
$response = $service->spreadsheets_values->batchUpdate("Spreadsheet ID goes here", $requestBody);
Print the response:
echo "<pre>";
print_r($response);
echo "</pre>";

ERROR: 6 - No data received from server in infusionsoft iSDK while adding contact

require_once APPPATH.'third_party/infusionsoft_api/iSDK/src/isdk.php';
class Infusion
{
$app = new iSDK;
if($app->cfgCon("infusionapi",$app_name, $api_key)) {
$conDat = array(
'FirstName' => 'ss',
'LastName' => 'aa',
'Email' => 'sachin.patil#gmail.com',
'StreetAddress1' => '11'
);
$conId = $app->addCon("Contact", $conDat);
echo "sss".$conId;
exit;
}
}
Sachin, are you checking to see if an error was generated? If an error is being thrown, you won't get back any return data but the error will be waiting for review in the result faultString() and result faultCode()

jira rest api error in creating issue

hi i am getting following error when trying to create an issue in jira using rest api with php.Error(s) creating issue:
object(stdClass)[1]
public 'errorMessages' =>
array (size=0)
empty
public 'errors' =>
object(stdClass)[2]
public 'summary' => string 'Field 'summary' cannot be set. It is
not on the appropriate screen, or unknown.' (length=79)
public 'description' => string 'Field 'description' cannot be
set. It is not on the appropriate screen, or unknown.' (length=83)
`
i am using the following source code:
<?php
define('JIRA_URL', 'xxxxxxxx');
define('USERNAME', 'xxxxxxxxx');
define('PASSWORD', 'xxxxxxxx');
function post_to($resource, $data) {
$curlname=CURLOPT_POST;
$curlvalue=1;
$jdata = json_encode($data);
$ch = curl_init();
curl_setopt_array($ch, array(
$curlname => $curlvalue,
CURLOPT_URL => JIRA_URL . '/rest/api/latest/' . $resource,
CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
function create_issue($issue) {
return post_to('issue', $issue);
}
$new_issue = array(
'fields' => array(
'project' => array('key' => 'xxx'),
'summary' => 'Test via REST',
'description' => 'Description of issue goes here.',
'issuetype' => array('name' => 'Task')
)
);
$result = create_issue($new_issue);
if (property_exists($result, 'errors')) {
echo "Error(s) creating issue:\n";
var_dump($result);
} else {
echo "New issue created at " . JIRA_URL ."/browse/{$result->key}\n";
}
?>
the fields with xxxx are replaced for security reason.
i want to know how i can correct this error.
While I see this was asked nearly a year ago, I'll go ahead and answer:
The "not on the appropriate screen, or unknown" error occurs because the account you're using does not have permission to view those fields.
Log into your JIRA instance with the account credentials you are providing to the service, and try to create a ticket in the same queue (project) that you are using as the value of $new_issue["fields"]["project"]["key"]. This is important, as different queues will have different permissions. When the form comes up with the fields for creating an issue, you likely will not see the "summary" and "description" fields. The account you're using will need to be added to the Administrator group (there are other groups with differing permissions, such as Developer and Member).

Error connecting to AuthorizeNet: in Production server only

I'm using Joomla with PHP, there is one component(payplans) is available for Joomla. In that component they configured lot of payment methods, including Authorize.net. We can select the payment method in the Joomla back-end, our client using Authorize.net so we selected Authorize.net.I did not change anything in the code, its working in our local m/c. I'm getting error only in live server even i have put the live account details not test account.
protected function _processNonRecurringRequest(PayplansPayment $payment, $data)
{
$transactionData = array(
'amount' => $payment->getAmount(),
'card_num' => $data['x_card_num'],
'exp_date' => $data['x_exp_date'],
'first_name' => $data['x_first_name'],
'last_name' => $data['x_last_name'],
'address' => $data['x_address'],
'city' => $data['x_city'],
'state' => $data['x_state'],
'country' => $data['x_country'],
'zip' => $data['x_zip'],
'email' => $data['x_email'],
'card_code' => $data['x_card_code'],
'ship_to_first_name' => $data['x_ship_to_first_name'],
'ship_to_last_name' => $data['x_ship_to_last_name'],
'ship_to_address' => $data['x_ship_to_address'],
'ship_to_city' => $data['x_ship_to_city'],
'ship_to_state' => $data['x_ship_to_state'],
'ship_to_zip' => $data['x_ship_to_zip'],
'ship_to_country' => $data['x_ship_to_country']
);
// echo "Data \n";
$transaction = new AuthorizeNetAIM();
$transaction->setSandbox(true);
$transaction->setFields($transactionData);
// print_r($transaction); exit();
// echo "response";
$response = $transaction->authorizeAndCapture();
// print_r($response);exit();
$transactionArray = $response->toArray();
// to identify it sis testing mode or not
$transactionArray['testmode'] = $this->getAppParam('sandbox', 0);
// save transaction notification and transaction id
if(isset($transactionArray['transaction_id'])){
$payment->set('txn_id', $this->getId().'_'.$transactionArray['transaction_id']);
}
$payment->set('transaction',PayplansHelperParam::arrayToIni($transactionArray));
$errors = array();
if($response->approved){
$payment->set('status',XiStatus::PAYMENT_COMPLETE);
}
else{
$payment->set('status',XiStatus::PAYMENT_PENDING);
$errors['response_reason_code'] = $response->response_reason_code;
$errors['response_code'] = $response->response_code;
$errors['response_reason_text'] = $response->response_reason_text;
}
return $errors;
}
I got error in this line
$response = $transaction->authorizeAndCapture();
please help
You have the following set to True:
$transaction->setSandbox(true);
Surely it should be set to false for the live server environment.

Categories