osclass SQL Inserting data twice - php

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.

Related

Inserting data from Coinbase API V2 into a MySQL Database using 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

cakephp multilingual dynamic content from database

I want to develop website with option to select language
at the time I do not know about how to structure my database tables i.e
either I should add separate fields for each language e.g
tbl_posts
id, title_en,title_fr,description_en,description_fr,....
or should I get help of google translate at run time
or there is something else easy to do this
secondly I will need to have URLs like
www.domain.com/en/posts/ & www.domain.com/fr/posts/
third what other things should I keep in mind to develop multilingual website.
looking for standardized, more optimized, easy manageable and fully dynamic solution.
Cakephp
Step 1: In your lib/Cake/basic.php add function
if (!function_exists('__dbt')) {
function __dbt($text, $args = null) {
if($text==null){
return null;
}else{
$languageUse = Configure::read('Config.language');
if($languageUse!='en-us' && $languageUse!='eng'){
$modelName = ucfirst($languageUse)."Translation";
$model = ClassRegistry::init($modelName);
$data = $model->find('first',array('fields'=>array('translation'),'conditions'=>array("text"=>"$text")));
if(!empty($data[$modelName]) && $data[$modelName]['translation']!=''){
return $data[$modelName]['translation'];//die('1');
}else{
// Please copy & paste below code from your basic.php __() function
App::uses('I18n', 'I18n');
$translated = I18n::translate($text);
$arguments = func_get_args();
return I18n::insertArgs($translated, array_slice($arguments, 1));
}
}else{
// Please copy & paste below code from your basic.php __() function
App::uses('I18n', 'I18n');
$translated = I18n::translate($text);
$arguments = func_get_args();
return I18n::insertArgs($translated, array_slice($arguments, 1));
}
}
}
}
Step 2: create table on basis of language you want to use
Note: table name should be prefix locale + _tranlations
example: hin_translations, tha_translations etc.
CREATE TABLE IF NOT EXISTS `hin_translations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` text NOT NULL,
`translation` text NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
In above table add english string in your text column and its translation in translation column.
Step 3: where ever you want to change language string either from database or locale po file just use
__dbt("Write your string here");
:) enjoy your multilingual site

Drupal: module update

I've module and I've update to alter database table, shortly I need to do something like
ALTER TABLE `TABLE` ADD `FIELD` INT UNSIGNED NOT NULL AFTER `SOME_FIELD`
so is there any built in function in Drupal to make this changes I considered db_add_field function didn't work?
Sultan
Using db_add_field()
db_add_field('TABLE', 'FIELD', "VARCHAR( 255 ) NOT NULL DEFAULT '0' AFTER FIELD_2");
The above does not work, for one it leaves out the first argument (the reference to $ret) and the fourth argument will not allow a raw sql query, only a structured array.
What I had to do was this (change hook_update_N to modulename_update_XXXX as per the drupal api documentation of course):
function hook_update_N(&$sandbox) {
// We use update_sql here, instead of db_add_field because we cannot specify
// AFTER in the db_add_field.
$ret = array();
$ret[] = update_sql("ALTER TABLE {table} ADD `FIELD` INT UNSIGNED NOT NULL AFTER `SOME_FIELD`");
return $ret;
}
Hope this helps someone else.

External linking and cakephp's routing engine (multilingual)

I recently build a tiny routing 'extension', that calls the routes from a MySQL table (structure downwards). I think it's worth to be mentioned, that this page runs in multiple languages (German and English). So - relying on the cookie, that's currently set in the client's browser - the corresponding routings get connected.
The problem is, that if the user cannot (externally) be linked to a german content page, if his browser's language cookie was set to the English language (because the english routes got connected).
Does anyone got a proper solution for this? To be honest, I don't really know, how to programmatically extend the Router-class' functionality.
The MySQL table's structure looks like this:
CREATE TABLE `routes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`language` varchar(5) COLLATE latin1_general_ci NOT NULL DEFAULT 'de',
`route` varchar(64) COLLATE latin1_general_ci NOT NULL,
`controller` varchar(64) COLLATE latin1_general_ci NOT NULL,
`action` varchar(64) COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (`id`)
)
Use p28n - http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial
It works well, I use it a lot and it's part of my standard build now.
I also have a script that will return translated urls depending on the chosen language. I can't remember where I found the script it's based on, but if it helps I can try to send you a clean version.
EDIT: Okay, here's the bones:
This script will translate urls so that they remain SEO friendly across languages. The language switching and message translation is handled by p28n (above) and po.
Put this line in your app/config/bootstrap.php file:
include_once("translate.php");
Put this as the first line of code in app/config/routes.php:
$fromUrl = translate($fromUrl,true);
Now you need to create the file app/config/translate.php which contains all of the routing information:
function translate($str = null,$total = false)
{
// If this is an RSS route, ignore it and bounce straight out
if (strpos($str,".rss")!==false)
return $str;
$translatetable = array(
'some-url-in-german' => array('/articles/msome-url-in-german',1),
'some-url-in-english' => array('/articles/some-url-in-german',2),
'a-german-article' => array('/posts/a-german-article',1),
'an-english-article' => array('/posts/a-german-article',2)
);
if($str)
{
if($total)
{
$old = explode('/',$str);
$lastone = end($old);
if(empty($lastone)) array_pop($old);
$new = array();
/* translate each part or leave untranslated part */
for($i = 0 ; $i <sizeof($old) ; $i++)
{
$new[$i] = translate($old[$i]);
}
/* construct the translated url. This also adds
a trailing "/" even if it wasn't in the original */
$new_url="";
foreach($new as $n)
{
$new_url .= $n."/";
}
return $new_url;
}
else
{
foreach ($translatetable as $orig => $new)
{
if($str == $orig)
{
$str = $new[0];
switchLanguage($new[1]);
}
}
return $str;
}
}
}
function switchLanguage($lang)
{
if($lang>0)
{
$translatetable = array(
'1' => 'de',
'2'=> 'eng'
);
Configure::write(array('Config.language'=>$translatetable[$lang]));
}
}
It's quite straightforward really - the trick is getting it to feed into CakePHP at the right places. I hope it is of some use to you.

(PHP & mySQL) Treat rows as columns

I am working on PHP & mySQL based website. I am trying to setup the 'Settings' page in administration panel where I can enter different settings to manage the site. The settings can range upto 100 (or even more) depending upon the requirements. So instead of making 100 columns (and increase if I have to add more columns in future), I want to store the data in row wise format and fetch the values as if I am fetching it from columns.
REFERENCE:
I found a similar real life implementation of such feature in the most popular blogging tool 'Wordpress'. For reference, it is the 'wp_options' table that I am talking about.(Please correct me I am wrong)
EXAMPLE:
Here's a quick example of what (& why) I am trying to do it that way:
--Table settings
P.KEY option_name option_value
1 site_name XYZ site inc.
2 siteurl http://www.xyz.com
3 slogan Welcome to my XYZ site
4 admin_email admin#xyz.com
5 mailserver_url mail.xyz.com
6 mailserver_port 23
..... etc.
As you can see from above, I have listed very few options and they are increasing in number. (Just for the records, my installation of Wordpress has 902 rows in wp_options table and I did not see any duplicate option_name). So I have the feeling that I am well off if I apply the same working principle as Wordpress to accomodate growth of the settings. Also I want to do it so that once I save all the settings in DB, I want to retrieve all the settings and populate the respective fields in the form, for which the entries exist in DB.
ONE OF MY CODE TRIALS:
--
-- Table structure for table `settings`
--
CREATE TABLE IF NOT EXISTS `settings` (
`set_id` tinyint(3) NOT NULL auto_increment,
`option_name` varchar(255) NOT NULL,
`option_value` varchar(255) NOT NULL,
PRIMARY KEY (`set_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `settings`
--
INSERT INTO `settings` (`set_id`, `option_name`, `option_value`) VALUES
(1, 'site_name', 'XYZ site inc.'),
(2, 'slogan', 'Welcome to my XYZ site');
$result = mysql_query("SELECT option_name, option_value FROM settings");
$defaults = array('option_name', 'option_value');
while( list($n, $v) = mysql_fetch_array($result) )
{
$defaults['option_name'] .= $n;
$defaults['option_value'] .= $v;
}
echo $defaults['option_name'].'---'.$defaults['option_value'].'<br />';
//The above code gives me the following Output:
//site_nameslogan---XYZ site inc.Welcome to my XYZ site
When I run the above query, I also receive 2 PHP Notices that says:
Undefined index: option_name
Undefined index: option_value
I would appreciate any replies that could show me the PHP code to retrieve the options successfully and eliminate the Undefined index issues as well. Also, like I mentioned earlier, I want to retrieve all the existing settings and populate the respective fields in the form when I visit the settings page next, after storing the data.
Thanks fly out to all in advance.
PHP gives you warning because $defaults['option_name'] and $defaults['option_value'] are not being initialized before they are used in .= operation.
So just put
$defaults['option_name'] = '';
$defaults['option_value'] = '';
before the loop and warning will go away.
The rest of the code is completely correct, although you don't have to have set_id column at all since every setting will have unique name, that name (option_name column) can be used as primary key.
Another thing that you can improve your code, is to use $defaults differently, like so
$defaults[$n] = $v;
Then you can use every setting on its own without looking through two huge strings.
$site_url = $defaults['site_url'];
foreach ($defaults as $name => $value) {
echo $name, ' = ', $value, '<br>';
}
This should do the trick:
$defaults = array('option_name' => array( ), 'option_value' => array( ) );
while( list($n, $v) = mysql_fetch_array($result) )
{
$defaults['option_name'][] = $n;
$defaults['option_value'][] = $v;
}
Then in your view iterate over $defaults['option_name'] and $defaults['option_value']

Categories