php mongodb findandmodify not working - php

I am using php and mongodb. I want to use findandmodify. My field is { "_id" : ObjectId("58d37e612d4ffa498b99c2d4"), "userid" : "1234", "active_time" : "hai" }
I want to modify active_time. For example change the value "hai" to "1234"
I am using MongoDB\Driver\Manager.
try {
$mng = new MongoDB\Driver\Manager("mongodb://username:password#localhost:27017/db");
$userid = '1234';
$retval = $mng->findAndModify(
array("userid" => $userid), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
$command = new MongoDB\Driver\Command($retval);
$cursor = $manager->executeCommand('db.online', $command);
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
It shows the error is
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::findAndModify()
in line
$retval = $mng->findAndModify(
array("userid" => $userid), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
How it possible? please help me?

I got the answer. Change the findAndModify to update. The modified code is shown below.
$bulk->update(
array("userid" => '1234'), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
$mng->executeBulkWrite("browser.online", $bulk);
if(!empty($mng)) {
echo "success";
} else {
echo "not";
}

Related

How to update a new atribute in Magento with CSV file thorugh API

I have a big numbers from Products in Magneto and i must add EAN Numbers to all the Products.
How could i update the new attribute from the CSV file through API.i want to update the EAN numbers from a ssh server through API SOAP.
This is not a full solution for you, but it is definitely a starting point for you. Good Luck
$productData = array(
'additional_attributes' => array(
'single_data' => array(
array(
'key' => 'ean',
'value' => 'value',
),
),
),
);
$productId = '1000000';
$soap = new SoapConnection('1','2','3');
echo $soap->_catalogProductUpdate($productId,$productData);
class SoapConnection
{
protected $soap_client;
protected $session_id;
function __construct($soap_host, $api_user, $api_pass)
{
try{
echo "Connecting to $soap_host\n";
$this->soap_client = new SoapClient( $soap_host, array('trace' =>true,
'connection_timeout' => 30,
'cache_wsdl' => WSDL_CACHE_NONE,
'keep_alive' => false
));
$this->session_id = $this->soap_client->login( $api_user, $api_pass);
echo "Connected with session id ".$this->session_id."\n";
return true;
} catch (SoapFault $e) {
echo "Soap Exception connecting to $soap_host: ". $e->getMessage(). "\n";
var_dump($this->soap_client->__getLastRequest()); var_dump($this->soap_client->__getLastResponse());
return false;
}
}
function _catalogProductUpdate($sku, $args)
{
try
{
return $this->soap_client->catalogProductUpdate($this->session_id, $sku, $args);
} catch (SoapFault $e) {
echo "Soap Exception _catalogProductUpdate: ". $e->getMessage(). "\n";
return false;
}
}
}
EDIT:
here is how to read a csv:
$file = fopen("my file path .csv","r");
while($row = fgetcsv($file))
{
$row[0];//column1
$row[1];//column2 etc etc etc
}
fclose($file);

catch error from a SOAP?

How to catch an error from a SOAP?
How can I avoid the fatal error and convert it to my own error.. In this example it's a SERVER_BUSY
code
class Validate_vatno {
private $client = null;
private $options = array(
'debug' => false
);
public function __construct(){
$this->client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('trace' => true));
}
public function check($country, $vatno){
$result = $this->client->checkVat(array(
'countryCode' => $country,
'vatNumber' => $vatno
));
if(!empty($this->options['debug'])){
echo '<pre>'.htmlentities($this->client->__getLastResponse()).'</pre>';
}
if($result->valid){
list($denomination, $name) = explode(' ', $result->name, 2);
return array(
'denomination' => utf8_decode($denomination),
'name' => ucwords(utf8_decode($name)),
'address' => ucwords(utf8_decode($result->address)),
);
}
else{
return array();
}
}
}
$vatValidation = new Validate_vatno();
if($return = $vatValidation->check('DK', 33214944)){
echo '<h1>valid one!</h1>';
echo 'denomination: ' . $return['denomination']. '<br/>';
echo 'name: ' . $return['name']. '<br/>';
echo 'address: ' . $return['address']. '<br/>';
}
else{
echo '<h1>Invalid VAT</h1>';
}
error
Fatal error: Uncaught SoapFault exception: [soapenv:Server] { 'SERVER_BUSY' } in /var/www/
Review how to handle exceptions
Throwing and Catching a Exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>

Trying to get property of non-object

i am inserting some data to an salesforce object named as Application__c from php using Soapclient. After connection successfull, i have written following code
$applications = array();
$updateFields = array();
if($_POST['savingsAccountBankName'] != ''){
$updateFields['savings_account_bank_name__c']= $_POST['savingsAccountBankName'];
}
if($_POST['AutoMake'] != ''){
$updateFields['Auto_make__c']= $_POST['AutoMake'];
}
if($_POST['AutoLicense'] != ''){
$updateFields['Auto_license__c']= $_POST['AutoLicense'];
}
$sObject = new sObject();
$sObject->type = 'Application__c';
$sObject->fields = $updateFields;
array_push($applications, $sObject);
try {
$results = $sforceClient->create($applications,'Application__c');
foreach ($results as $result)
{
$errMessage = $result->errors->message;
echo $errMessage;
}
} catch (Exception $e) {
echo 'Salesforce Upsert Error. Please try again later.';
echo '<pre>';
print_r($e);
echo '</pre>';
}
i am getting error "Trying to get property of non-object" at line "$errMessage = $result->errors->message;". What is the problem?
thanks
Be aware that $result is an array..
Try this :
if (!isset($result[0]->success) || ($result[0]->success!=1)) {
$strErrCode = isset($result[0]->errors[0]->statusCode)?
$result[0]->errors[0]->statusCode:'CANNOT_INSERT';
$strErrMsg = isset($result[0]->errors[0]->message)?
$result[0]->errors[0]->message:'Error Trying to insert';
$arrResult = array(
'errorCode' => $strErrCode,
'errorMsg' => $strErrMsg,
'id' => '',
);
error_log( 'Error Trying to insert - [' . $strErrMsg . '] - [' . $strErrCode . ']');
}
if (isset($result[0]->success) && ($result[0]->success==1)) {
$arrResult = array(
'errorCode' => 'SUCCESS_INSERT',
'errorMsg' => 'Insert Success',
'id' => isset($result[0]->id)?$result[0]->id:'1',
);
error_log( 'Success insert - [' . (isset($result[0]->id)?$result[0]->id:'1') . ']');
}
This means that whatever $results contains, it is not an object. Try doing a var_dump() on the variable $results and see what is actually in there. Then you can properly reference it.

eWay Payment Gateway

I'm trying to implement the recurring web service from eway(australia).How ever I could not get it to work.
I keep on getting the messeage
"The element 'rebillCustomerCreate' in namespace 'http://www.eway.com.au/gateway/rebill/manageRebill' has incomplete content. List of possible elements expected: 'CustomerRef'."
This is the WSDL: https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl
I am new to SOAP. Trying to implement it in PHP. Can anyone please point out what I did wrong?
Here is my php Code:
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions =array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"customerTitle" => "Mr",
"customerFirstName" => "firstname",
"customerLastName" => "lastname",
"customerAddress" => "address",
"customerSuburb" => "someniceplace",
"customerState" => "somenicestate",
"customerCompany" => "somecompany",
"customerPostCode" => "411026",
"customerCountry" => "australia",
"customerEmail" => "test#eway.com",
"customerFax" => "123456",
"customerPhone1" => "123456",
"customerPhone2" => "123456",
"customerRef" => "abc123",
"customerJobDesc" => "Developer",
"customerComments" => "Make it work",
"customerURL" => "www.nicesite.com"
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
var_dump($response);
} catch(SOAPFault $e){
print $e;
}
?>
What I tried to create eWay recurring billing and customer,
hope it will help for others new :)
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions =array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test123");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
"customerFirstName"=>"Muhammad",
"customerLastName"=>"Shahzad",
"customerAddress"=>"cust ome rAddress",
"customerSuburb"=>"customer Suburb",
"customerState"=>"ACT",
"customerCompany"=>"customer Company",
"customerPostCode"=>"2345",
"customerCountry"=>">Australia",
"customerEmail"=>"test#gamil.com",
"customerFax"=>"0298989898",
"customerPhone1"=>"0297979797",
"customerPhone2"=>"0297979797",
"customerRef"=>"Ref123",
"customerJobDesc"=>"customerJobDesc",
"customerComments"=>"customerComments",
"customerURL" => "http://www.acme.com.au"
)
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
//echo "<pre>";echo "<br/>";
// print_r($response);
echo $result = $response->CreateRebillCustomerResult->Result;echo "<br/>";
echo $customerId = $response->CreateRebillCustomerResult->RebillCustomerID;echo "<br/>";
echo "<br/>";
if($result=='Success' AND $customerId){
echo 'Member Created at eWay Successfully!...<br/>';
echo 'Creating Recurring Billing Cycle on eWay,Please wait......<br/>';
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillCustomerResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillCustomerResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
if($customerId){
$bodyoptions2 = array(
"CreateRebillEvent " => array(
"RebillCustomerID" => $customerId,
"RebillInvRef" => "Ref123",
"RebillInvDes"=>"description",
"RebillCCName"=>"Mr Andy Person",
"RebillCCNumber"=>"4444333322221111",
"RebillCCExpMonth"=>"12",
"RebillCCExpYear"=>"15",
"RebillInitAmt"=>"100",
"RebillInitDate"=>date('d/m/Y'),
"RebillRecurAmt"=>"200",
"RebillStartDate"=>date('d/m/Y'),
"RebillInterval"=>"31",
"RebillIntervalType"=>"1",
"RebillEndDate"=>"31/12/2013",
)
);
try{
$response = $client->__soapCall("CreateRebillEvent", $bodyoptions2,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//print_r($response);
echo "<br/>";
echo $result2 = $response->CreateRebillEventResult->Result;echo "<br/>";
echo $RebillCustomerID = $response->CreateRebillEventResult->RebillCustomerID;echo "<br/>";
if($result2=='Success'){
echo 'Recurring Cycle Created Successfully at eWay!...<br/>';
echo 'Member Id is ===>'.$RebillCustomerID;
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillEventResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillEventResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
}
?>
I suggest you to use the library and sample provided by eWay.
Go to this page. Go to "Source Code" tab. The, download PHP source code. There is instruction also.
2 years later, I've just had the very same issue !
Might be useful to someone:
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
...
)
);

Fatal error: Call to undefined method stdClass::stream_publish()

Well I am trying to post on facebook's wall but I get this error:
Fatal error: Call to undefined method stdClass::stream_publish()
The code I am trying is this
<?php
define('FB_APIKEY', '<Your Api Key>');
define('FB_SECRET', '<Secret>');
define('FB_SESSION', '<Session>');
require_once('facebook.php');
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = '';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'Visit Us', 'href' => '<link to some place here>'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "<Target Id>";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
Well, as it is written in the error message there is no method "stream_publish" in $facebook->api_client.
Consult the manual of the library you are using to connect to the facebook.
If $facebook->api_client is not an object, then the line:
$facebook->api_client->session_key = FB_SESSION;
Will make php silently cast $facebook->api_client to an object of type stdClass. Which, later on down the code, will cause the Fatal error: Call to undefined method stdClass::stream_publish() that you are getting.
Try changing:
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
to catch for when api_client is false (or, perhaps, not an object):
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
if (!( $facebook->api_client )) {
//throw error
echo 'Need to sort this bit out';
exit;
}
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
And then, if that does throw an error, you'd need to investigate why $facebook->api_client is null.

Categories