Inserting data from Coinbase API V2 into a MySQL Database using php - php

I'm a bit stuck here. I'm building an app based on the Coinbase PHP API V2.
This is what I'm trying to achieve. I would like to place the currency code (for e.g. EUR or USD) and the corresponding sell price at the moment of calling in my local MySQL database (ideal also including a timestamp).
I'm getting this info by using the method: getSellPrice(). This method returns this info:
Coinbase\Wallet\Value\Money Object ( [amount:Coinbase\Wallet\Value\Money:private] => 2250.47 [currency:Coinbase\Wallet\Value\Money:private] => USD )
So far so good. But how do I get these values saved in my database? Breaking it down I have the following sub-questions:
How do extract the values "amount=>2250.47" and "currency=>USD"?
How do I save these 2 values in the corresponding columns "amount" and "currency" in my database?
What exact script do I need /steps to follow?
Just some general info. I'm using XAMPP as local server.
This is the code which I have so far:
`
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
//Connect with credentials.
$apiKey = 'xxx';
$apiSecret = 'xxx';
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
$sellPrice = $client->getSellPrice('BTC-USD');
print_r ($sellPrice);
//So far it works fine.
?>
`
I have set up a table by using this query:
`CREATE TABLE `data` (
`id` BIGINT UNSIGNED NOT NULL ,
`time_stamp` BIGINT UNSIGNED NOT NULL ,
`currency` VARCHAR( 255 ) NOT NULL ,
`amount` BIGINT UNSIGNED NOT NULL ,
PRIMARY KEY ( `id` )
);
`
Every help is welcome or pointing me in the right direction. And is much appreciated!
Cheers

There is a method, which gets you the response in a raw format.
Check out $data = $client->decodeLastResponse();
It's taken from the original documentation on git.

TRY This code to get amount and currency
$sellPrice = $client->getSellPrice('BTC-USD');
$amount=$sellPrice->getAmount();
$currency=$sellPrice->getCurrency();
Hope it will work

Related

osclass SQL Inserting data twice

i have this osclass table when I insert a data and then browse the table the data has been entered twice, so i get two id of the same table.
CREATE TABLE /*TABLE_PREFIX*/t_table_log(
pk_i_id INT NOT NULL AUTO_INCREMENT ,
fk_i_user_id INT NULL ,
fk_i_item_id INT NULL ,
s_email VARCHAR( 200 ) NULL ,
s_status VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY(pk_i_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET 'UTF8' COLLATE 'UTF8_GENERAL_CI';
this is my php code
$conn = getConnection();
$conn->osc_dbExec("INSERT INTO %st_table_log (fk_i_item_id, fk_i_user_id, s_email, s_status ) VALUES ('".$_SESSION['itemid']."','".$_SESSION['userid']."','".$response['senderEmail']."','".$response['status']."')", DB_TABLE_PREFIX) ;
$item_url = osc_item_url() ;
$name = osc_page_title() ;
$subject = (__("Hello",'osclass'));
$email = osc_logged_admin_email();
$messagesend =" my message";
$params = array(
'subject' => $subject
,'to' => $email
,'to_name' =>$name
,'body' => $messagesend
,'alt_body' => strip_tags($messagesend)
) ;
osc_sendMail($params) ;
Where's located your code?
You might want to check those things:
autocron: this is an Osclass-feature that runs Cron without the need to configure the crontab. Head to Settings > General and check if autocron is checked. It makes a new HTTP request for it, so your code might be running twice.
ajax: you might have some ajax query in one of your enabled plugins or theme that makes a request on each loading and run your code twice.
From what I see, you might want to use the 'init' hook to be sure it gets executed once. Something like this:
osc_add_hook('init', function () {
$session = Session::newInstance();
$userId = $session->_get('userid');
$itemId = $session->_get('itemid');
// Do something.
});
Also, try to take a look at DAO in Osclass and plugin development, here's a tutorial that will get you through Osclass plugin development and the use of DAO.

OpenERP XML-RPC PHP insert into re.users with company_id

I'm trying to insert in res.users with this code:
$values= array(
"name"=>new xmlrpcval($name,"string"),
"login"=>new xmlrpcval($login,"string"),
"password"=>new xmlrpcval($psw,"string"),
"lang"=>new xmlrpcval("it_IT","string"),
"company_id"= new xmlrpcval($company,"many2one");
);
echo $id= $this->create($values,"res.users");
I'm using a user with all the possible privileges.
The function returns a -1 state that means that I've no permission or the format is not corrected.
It works if I remove the company_id field.
try this,
Many2one is store int id of record created. So in company_id pass int in format.
$values= array(
"name"=>new xmlrpcval($name,"string"),
"login"=>new xmlrpcval($login,"string"),
"password"=>new xmlrpcval($psw,"string"),
"lang"=>new xmlrpcval("it_IT","string"),
"company_id"= new xmlrpcval($company,"int");
);
echo $id= $this->create($values,"res.users");

How to avoid the nulll values when i load the datas using dataprovider

I have one doubt in data provider,
I have more number of fields in the db.If i retrieve the data in specific field,it fetch null values as well as exist values are shown here.I want only the exist values .Without null values i want to load the vales How to do that...Anyone know please help me.
For example C grid view data provider 5 rows have null values in db and another 5 rows have values i want load without null values..please help me.. :(
public function actionDataProvider {
$uid=Yii::app()->user->id;
if(isset($_GET['user_id']))
$uid=$_GET['user_id'];
$criteria = new CDbCriteria();
$criteria->condition=("user_id= $uid ");
$dataProvider=new CActiveDataProvider('UserGallery',array('criteria'=>$criteria,'pagination'=>array('pageSize'=>20)));
$this->render('product_pic',array('model' => userGallery::model()->findAll($criteria),'dataProvider'=>$dataProvider,));
}
Append to your other $criteria's:
To show NULL values,
$criteria->addInCondition( 'columnWithNull', array( null ) );
To hide NULL values:
$criteria->addNotInCondition( 'columnWithNull', array( null ) );
I found this in Yii documentation (in really reading CDBCriteria source code).

CakePHP - Why does Model::save cause() an INSERT instead of an UPDATE?

I want to update database in CAKEPHP's Way
this is my controller
$data = array(
'KnowledgeBase' => array(
'kb_title' => $this->data['KnowledgeBase']['kb_title'],
'kb_content' => $this->data['KnowledgeBase']['kb_content']
'kb_last_update' => date("Y-m-d G:i:s"),
'kb_segment' => $this->data['KnowledgeBase']['kb_segment']
));
$this->KnowledgeBase->id_kb = $this->data['KnowledgeBase']['id_kb'];
$this->KnowledgeBase->save($data);
assume I have post form is true, when I execute the program
I have some error like this :
Database Error
Error: SQLSTATE[23000]: [Microsoft][SQL Server Native Client 10.0]
[SQL Server]Violation of PRIMARY KEY constraint 'PK_cnaf_kb'.
Cannot insert duplicate key in object 'dbo.cnaf_kb'.
SQL Query: INSERT INTO [cnaf_kb] ([kb_judul], [kb_segment], [kb_isi], [id_kb], [kb_last_update], [kb_status]) VALUES (N'HARRIS TEST 4 ', N'4', N'<p>TESSSSSSSSSSSSSSSSSSSSSS</p> ', 73,
'2013-10-04 16:57:00', 1)
why the function use the insert query? not update ?
note : im not using form helper for post to controller, and I use Cakephp 2.3.8 version and sql server 2008 for database
Im sorry for my bad english, I hope someone can help me :(((
You do not supply a primary key value, that's why.
No matter what your primary key is named (Model::$primaryKey), on the model object you have to use the id property (Model::$id) if you want to set the primary key value.
$this->KnowledgeBase->id = $this->data['KnowledgeBase']['id_kb'];
Internally the model maps this to the appropriate primary key field.
In the data however you'd use the actual primary key name:
'id_kb' => $this->data['KnowledgeBase']['id_kb']
btw, I'm not sure why you are (re)building the data array, but if it's to make sure that only specific fields are saved, then you could use the fieldList option instead:
$this->data['KnowledgeBase']['kb_last_update'] = date('Y-m-d G:i:s');
$options = array(
'fieldList' => array(
'kb_title',
'kb_content',
'kb_last_update',
'kb_segment'
)
);
$this->KnowledgeBase->save($this->data, $options);

How can I group by column value in a yii query?

I have a data table with 7 columns and 400 records. One of them is budget. I want to group the 400 rows by budget so that I get an array like this:
[budget]=>array(
[0]=>array(
[column1]=>'1',
[column2]=>'sand'
),
[1]=>array(
[column1]=>'2',
[column2]=>'clay'
)
)
[budget2]=>array(
[0]=>array(
[column1]=>'3',
[column2]=>'silt'
),
[1]=>array(
[column1]=>'4',
[column2]=>'stone'
)
)
So far I have been playing around with Yii's CdbCommand and CdbDataReader and PHP's PDOStatement but nothing is working right. I tried the following code
public function actionBidCostByBudget(){
$command = Yii::app()->db
->createCommand()
->Select('*')
->From('bid_cost')
# ->Query()
;
echo '<pre>';
echo get_class($command);
$pdostatement=$command->getPdoStatement();
if($pdostatement) echo get_class($pdostatement);
# print_r($statement->fetchall(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
# print_r($command->readall());
# print_r($statement->fetch());
# $columnsArray = BidCost::attributeLabels();
//print_r($rowsArray);
//$this->layout='\\layout';
}
The attempts to print_r all print out with nothing. getPdoStatement equals nothing. I have been trying to use PDO::FETCH_COLUMN|PDO::FETCH_GROUP as per the Php.net website, but it does not work either because I get nothing.
One of Yii's strengths is it's ActiveRecord, so why not use it?
Make your budget to a separate table (so you can generate a model from it). Reference it from your "datatable".
CREATE TABLE budget (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE datatable(
column1 TEXT,
column2 TEXT,
...
budget_id INTEGER,
FOREIGN KEY(budget_id) REFERENCES budget(id)
);
Next generate models with Gii, and now you can use your newly made relations like this:
$budget = Budget::model()->findByAttributes( ["name"=>"budget2"] );
foreach( $budget->datatables as $dt ) {
echo $dt->column1;
echo $dt->column2;
}
(I know. Not the array you asked for. Sorry if I'm way off with this.)
Alright, the bottom line is that I was not able to find a way to do this right thru Yii, so I did it with a more hands-on approach.
The first thing I did was basically initiate a database connection thru Yii.
$command = Yii::app()->db //outputs CDbConnnection
The next thing I did was get a PDO class from the connection:
$pdoinstance = $command->getPdoInstance(); //outputs PDO class
From this point, it was help obtained from PHP.net and another question posted on this forum:
$pdostatement=$pdoinstance->prepare('SELECT BUDGET_CODE,
PAY_ITEM, ITEM, DESCRIPTION FROM bidcost');
$pdostatement->execute();
//default fetch mode could not be set
# $pdostatement->setfetchmode(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
//returns array
$testarray=$pdostatement->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

Categories