I am trying to extract 4 rows of product prices from a database table.
AU$ 11.00
AU$ 19.00
AU$ 32.00
AU$ 52.00
When i execute the code below i only retrieve the last value AU$ 52.00 from the database.
Array ( [CURRENCY] => AU$ 52.00 )
This is my code
$sql = DB::getInstance()->query('SELECT monthly FROM products');
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
}
$currency = array(
'CURRENCY' => $price,
);
print_r($currency['CURRENCY']);
die();
?>
Probably overlooking somthing simple but my head is all bitter and twisted now. Any help will be useful. Thanks in advance
EDIT TO QUESTION
This will be a currency converter so the code below may help with how it will work
$currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
$get_cur = Input::get('currency');
if(isset($get_cur) === true && in_array($get_cur, $currencies) === true) {
$_SESSION['currency'] = $get_cur;
} else if (isset($_SESSION['currency']) === false) {
$_SESSION['currency'] = 'AUD';
}
include 'currency/' . $_SESSION['currency'] . '.php';
From each linked currency will go to AUD, USD, GBP etc etc
<a href="?currency=AUD">
Linked to AUD.php which is the code from the original question. This is why i need to link
$currency['CURRENCY']
This will be the defined name in the array of each currency.
Hope this helps
EDIT TO QUESTION #2
<?php
// Currency Covert Class
class CurrencyConverter {
public function convert($amount, $from, $to) {
$data = file_get_contents('https://www.google.com/finance/converter?a=' . $amount . '&from=' . $from . '&to=' . $to);
preg_match("/<span class=bld>(.*)<\/span>/", $data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return $converted;
}
}
////////////////////////
$currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
$get_lang = Input::get('currency');
if(isset($get_lang) === true && in_array($get_lang, $currencies) === true) {
$_SESSION['currency'] = $get_lang; //Get's the currency from whichever currency is selected from the $currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
} else if (isset($_SESSION['currency']) === false) {
$_SESSION['currency'] = 'AUD'; //If no currency selected, then default is AUD
}
include 'currency/' . $_SESSION['currency'] . '.php'; //Selects the currenct .php file eg; 'AUD', 'USD', 'GBP', 'EUR', 'THB'
//If AUD.php then it $_GET currency eg; ?currency=AUD, ?currency=USD, ?currency=GBP
// This is AUD.php (DEFAULT CURRENCY)
$sql = DB::getInstance()->query('SELECT monthly FROM products');
foreach($sql->results() as $row) {
$currency = array(
'CURRENCY' => '<small>AU$</small> ' . number_format($row->monthly, 2),
);
}
// This is USD.php
$converter = new CurrencyConverter;
$sql = DB::getInstance()->query('SELECT monthly FROM products');
foreach($sql->results() as $row) {
$currency = array(
'CURRENCY' => '<small>US$</small> ' . number_format($converter->convert($row->monthly, 'AUD', 'USD'), 2),
);
}
//So you can see that all the currency .php files have the key array word of 'CURRENCY', and this is how it will work from the $_SESSION['currency'] to the $currency['CURRENCY'] array
//Then simply echo out $currency['CURRENCY'] and it will convert to each $currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
echo '<p>' . $currency['CURRENCY'] . '<span>' . $lang['PER_MONTH'] . '</span></p>';
?>
EDIT TO QUESTION #3
I think i have found the issue, overlooked by me. It is inside a nested foreach loop
$sql = DB::getInstance()->query('SELECT * FROM products ORDER BY id ASC');
foreach($sql->results() as $row) {
if(escape($row->popular)) {
echo '<div class="col-md-3 price-table ' . escape($row->popular) . '">';
} else {
echo '<div class="col-md-3 price-table">';
}
?>
<h3><strong><?php echo escape($row->name) ?></strong><br><?php echo $lang['PACKAGE'] ?></h3>
<?php
///HERE IS WHERE IT GETS PULLED IN FROM AUD.php, USD.php, GBP.php, etc etc///
///START OF AUD.php///
$sql = DB::getInstance()->query('SELECT monthly FROM products');
$currency = array();
$currency['CURRENCY'] = array();
foreach($sql->results() as $row) {
array_push($currency['CURRENCY'], '<small>AU$</small> ' . number_format($row->monthly, 2));
}
///END OF AUD.php///
echo '<p>' . implode($currency['CURRENCY'], ' <span>' . $lang['PER_MONTH'] . '</span>') . '</p>';
The arrays is below
Array
(
[0] => AU$ 11.00
[1] => AU$ 19.00
[2] => AU$ 32.00
[3] => AU$ 52.00
)
I need it like this to be able to convert the currencies. So i need this;
echo '<p>' . implode($currency['CURRENCY'], ' <span>' . $lang['PER_MONTH'] . '</span>') . '</p>';
To echo out below in the first pass of the loop
echo '<p> AU$ 11.00 <span>Per Month</span></p>';
And echo out below in the second pass of the loop
echo '<p> AU$ 19.00 <span>Per Month</span></p>';
And so on. At the moment i am getting all four values on every pass of the loop
You arent adding the value in your loop so you only get the last value in $price
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
$currency[]=array('CURRENCY' => $price);
}
Do this. it will do it perfectly
$sql = DB::getInstance()->query('SELECT monthly FROM products');
$currency = array();
$i=0;
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
$currency['CURRENCY'][$i] = $price;
$i++;
}
print_r($currency['CURRENCY']);
?>
Do this:
$currency = array();
$currency['currency'] = array()
foreach($sql->results() as $row) {
array_push($currency['currency'], '<small>AU$</small> ' . number_format($row->monthly, 2));
}
echo '<p>' . implode($currency['CURRENCY'], ' <span>' . $lang['PER_MONTH'] . '</span><br />') . </p>';
Now foreach will push a value into the array $currency, with the correct currency.
Close foreach loop after you have assigned price to currency.
$currency = array();
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
$currency[] = $price;
}
Related
public function getShoppingCartAbandonmentinfo($params){
$final_array=array();
require_once(DIR_WS_MODEL . "UserMaster.php");
require_once(DIR_WS_MODEL . 'OrderExportMaster.php');
require_once(DIR_WS_MODEL . 'BasketMaster.php');
require_once (DIR_WS_MODEL . "/ProductsMaster.php");
require_once (DIR_WS_MODEL . "/ProductPriceMaster.php");
$objProductsMaster = new ProductsMaster();
$objProductPriceMaster = new ProductPriceMaster();
$ObjUserMaster = new UserMaster();
$UserData = new UserData();
$ObjBasketMaster = new BasketMaster();
$ObjBasketData = new BasketData();
$ObjOrderExportMaster = new OrderExportMaster();
$ObjOrderExportData = new OrderExportData();
define_const(PRODUCT_SEPARATOR, '||');
$static_cust_array = array('firstname' => 'user_master.firstname AS first_name','lastname' => 'user_master.lastname AS last_name','companyname' => 'user_master.companyname AS company_name','email' => 'user_master.email','user_id' => 'user_master.userid','customer_type'=>'user_master.customer_type AS guest_customer');
$ObjBasketMaster->setSelect("user_master.userid")->setSelect((array)$static_cust_array);
$ObjBasketMaster->setJoin("LEFT JOIN user_master ON user_master.userid=user_basket.user_id");
$customer_details = $ObjBasketMaster->getBasket();
foreach ($customer_details as $customer_field_value){
$output='';
foreach ($customer_field_value as $field_key => $customer_details_value){
if($field_key == 'guest_customer' ){
$field_key ="guest_user";
if($customer_details_value == 1){
$customer_details_value = "NO";
}else{
$customer_details_value = "YES";
}
}
$output[$field_key]= $customer_details_value;
$all['customer_details']=$output;
}
$output1[]= $all;
}
//echo "<pre>";print_r($output1);echo "</pre>";exit;
/*Shopping Cart Loop */
$static_basket_array=array('basket_id'=>'user_basket.basket_id','user_basket.date'=>'date AS created_date','cart_detail'=>'user_basket.cart_detail AS products');
$ObjBasketMaster->setSelect((array)$static_basket_array);
$ObjBasketMaster->setSelect('user_basket.date AS abandoned_days');
$ObjBasketMaster->setJoin("LEFT JOIN user_master ON user_master.userid=user_basket.user_id");
$cart_details = $ObjBasketMaster->getBasket();
foreach ($cart_details as $cart_field_value){
$output='';
foreach ($cart_field_value as $field_key => $cart_details_value){
if($field_key == 'abandoned_days' ){
$OldDate = $cart_details_value;
$now = time(); // or your date as well
$your_date = strtotime($OldDate);
$datediff = $now - $your_date;
$cart_details_value=round($datediff / (60 * 60 * 24));
}
if($field_key == 'products' && !empty($cart_details_value) ){
$cart_data=unserialize($cart_details_value);
foreach ($cart_data as $key => $data){
$objProductsMaster->setSelect('products_title');
$objProductsMaster->setWhere("AND products_id = :products_id",$data['product_id'],'int');
$objProductsMaster->setWhere('AND site_language_id = :site_language_id', SITE_LANGUAGE_ID, 'int');
$datad = $objProductsMaster->getProductsDesc();
$products= array('product_id'=>$data['product_id'],'product_title'=>$datad[0]['products_title']);
}
$cart_details_value=array();
$cart_details_value= $products;
}
$output[$field_key]= $cart_details_value;
$all['shopping_cart']=$output;
}
echo "<pre>";print_r($output1);echo "</pre>";exit;
$output1[]= $all;
}
/*End OF Shopping Cart */
if(empty($output1))
$output=array('Message'=>NO_RECORD_FOUND);
return $output1;
}
}
Here in $output1 i always get the latest data, but i want all the data . The data is been over written in $output1 .
So how can i add $customer_details_value as well as $cart_details_value both in $output1.
Here after adding $cart_details_value in $output it over rides value of $customer_details_value in $output1
You need to define your $output1 before the loops:
$output1 = [];
And better start using informative variable names, to easy read the code and find the errors.
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 */
I am stuck with a problem in php, mysql and json
I am not able to retrieve data from the database by selecting two conditions
I have attached a screenshot as well
I want to retrieve the quantity from table customer_stock by considering two conditions: customer and name
$line = $db->queryUniqueObject("SELECT * FROM stock_details WHERE stock_name ='" . $_POST['stock_name1'] . "'");
$cost = $line->company_price;
$sell = $line->selling_price;
$stock_id = $line->stock_id;
$line = $db->queryUniqueObject("SELECT * FROM customer_stock WHERE name='" . $_POST['stock_name1'] . "'");
$stock = $line->quantity;
if ($line != NULL) {
$arr = array("cost" => "$cost", "sell" => "$sell", "stock" => "$stock", "guid" => $stock_id);
echo json_encode($arr);
} else {
$arr1 = array("no" => "no");
echo json_encode($arr1);
}
<?php
/**
* #author stw
* #website http://stw-services.com/
*
*/
header('Content-Type: text/csv; charset=utf-8');
require_once("app/Mage.php");
Mage::app('default');
/*$csv_file = "juliajune_erp/import/products/products.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
*/
$row = 0;
$simple_product_counter=0;
$simple_product_sku[]=array();
$simple_product_color[]=array();
$simple_product_size[]=array();
$path = "juliajune_erp/import/products/export/";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
$latestpath = $path.$latest_filename;
if (($handle = fopen($latestpath, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
$num = count($data);
$row++;
if($data[3] == 'simple')
{
$simpleProduct = Mage::getModel('catalog/product');
try {
//echo "set attribute:-".$data[2];echo "<br>";
//$simpleProduct->setAttributeSetId(4); //ID of a attribute set named 'default'
if($data[2]=='Default'){$attribute_set_id=4;}
$simpleProduct->setAttributeSetId($attribute_set_id); //ID of a attribute set named 'default'
//echo "product type:-".$data[3];echo "<br>";
$simpleProduct->setTypeId($data[3]); //product type
//echo "created time:-".$data[11];echo "<br>";
$simpleProduct->setCreatedAt($data[11]); //product creation time
//echo "sku:-".$data[0];echo "<br>";
$simpleProduct->setSku($data[0]); //SKU
//echo "name:-".$data[36];echo "<br>";
$simpleProduct->setName($data[36]); //product name
//echo "weight:-".$data[59];echo "<br>";
$simpleProduct->setWeight($data[59]);
//echo "status:-".$data[50];echo "<br>";
$simpleProduct->setStatus($data[50]); //product status (1 - enabled, 2 - disabled)
//echo "tax class id:-".$data[51];echo "<br>";
$simpleProduct->setTaxClassId($data[51]); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
//echo "visibility :-".$data[58];echo "<br>";
$simpleProduct->setVisibility($data[58]); //catalog and search visibility
/*----------color------------*/
$attributeColorCode = 'color';
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributeColorCode);
if ($attr->usesSource()) { $color_id = $attr->getSource()->getOptionId($data[8]); }
//echo "color :-".$color_id;echo "<br>";
$simpleProduct->setColor($color_id);
/*----------size------------*/
$attributeSizeCode = 'size';
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributeSizeCode);
if ($attr->usesSource()) { $size_id = $attr->getSource()->getOptionId($data[44]); }
//echo "size :-".$size_id;echo "<br>";
$simpleProduct->setSize($size_id);
//echo "price:-".$data[41]; echo "<br>";
$simpleProduct->setPrice($data[41]); //price in form 11.22
//echo "msrp enable:-".$data[35];echo "<br>";
$simpleProduct->setMsrpEnabled(2); //enable MAP
//echo "msrp display actual price type:-".$data[34];echo "<br>";
$simpleProduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
//echo "description:-".$data[20];echo "<br>";
$simpleProduct->setDescription($data[20]);
//echo "short description:-".$data[43];echo "<br>";
$simpleProduct->setShortDescription($data[43]);
$mediaArray_simple = array('thumbnail' => $data[52],'small_image' => $data[45],'image' => $data[25]);
$importDir_images = Mage::getBaseDir('media') . DS . 'import/';
//foreach ( $mediaArray_simple as $imageType => $fileName ) {
$fileName = $data[25];
$filePath = $importDir_images.$fileName;
if ( file_exists($filePath) ) {
//$simpleProduct->addImageToMediaGallery($filePath, $imageType, false);
$simpleProduct->addImageToMediaGallery($filePath, array('image','thumbnail','small_image'), false, false);
}
//}
$stockData = $simpleProduct->setStockData(array(
'use_config_manage_stock' => $data[74], //'Use config settings' checkbox
'manage_stock' => $data[73], //manage stock
'is_in_stock' => $data[70], //Stock Availability
'qty' => $data[60] //qty
)
);
//echo "category id:-".$data[4];echo "<br>----------------<br>";
$simpleProduct->setCategoryIds(array('')); //assign product to categories
$simpleProduct->save();
/* using for configurable product */
$simple_product_sku[$simple_product_counter]=$data[0];
$simple_product_color[$simple_product_counter]=$data[8];
$simple_product_size[$simple_product_counter]=$data[44];
$simple_product_counter++;
} catch (Exception $e) {
Mage::log($e->getMessage());
//echo $e->getMessage();
}
}elseif($data[3] == 'configurable'){
$configProduct = Mage::getModel('catalog/product');
try {
//echo "set attribute:-".$data[2];echo "<br>";
//$configProduct->setAttributeSetId(4); //ID of a attribute set named 'default'
if($data[2]=='Default'){$attribute_set_id=4;}
$configProduct->setAttributeSetId($attribute_set_id); //ID of a attribute set named 'default'
//echo "product type:-".$data[3];echo "<br>";
$configProduct->setTypeId($data[3]); //product type
//echo "created time:-".$data[11];echo "<br>";
$configProduct->setCreatedAt($data[11]); //product creation time
//echo "sku:-".$data[0];echo "<br>";
$configProduct->setSku($data[0]); //SKU
//echo "name:-".$data[36];echo "<br>";
$configProduct->setName($data[36]); //product name
//echo "weight:-".$data[59];echo "<br>";
$configProduct->setWeight($data[59]);
//echo "status:-".$data[50];echo "<br>";
$configProduct->setStatus($data[50]); //product status (1 - enabled, 2 - disabled)
//echo "tax class id:-".$data[51];echo "<br>";
$configProduct->setTaxClassId($data[51]); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
//echo "visibility :-".$data[58];echo "<br>";
$configProduct->setVisibility($data[58]); //catalog and search visibility
//echo "price:-".$data[41]; echo "<br>";
$configProduct->setPrice($data[41]); //price in form 11.22
//echo "msrp enable:-".$data[35];echo "<br>";
$configProduct->setMsrpEnabled(2); //enable MAP
//echo "msrp display actual price type:-".$data[34];echo "<br>";
$configProduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
//echo "description:-".$data[20];echo "<br>";
$configProduct->setDescription($data[20]);
//echo "short description:-".$data[43];echo "<br>";
$configProduct->setShortDescription($data[43]);
$mediaArray = array('thumbnail' => $data[52],'small_image' => $data[45],'image' => $data[25]);
$importDir_images = Mage::getBaseDir('media') . DS . 'import/product_images/';
$fileName = $data[36];
$filePath = $importDir_images.$fileName.'.jpg';
if ( file_exists($filePath) ) {
$configProduct->addImageToMediaGallery($filePath, array('image','thumbnail','small_image'), false, false);
}
for($img_i=1;$img_i<=4;$img_i++)
{
$importDir_images = Mage::getBaseDir('media') . DS . 'import/product_images/';
$fileName = $data[36];
$filePath = $importDir_images.$fileName.'_'.$img_i.'.jpg';
if ( file_exists($filePath) ) {
$configProduct->addImageToMediaGallery( $filePath , null, false, false );
}
}
$stockData = $configProduct->setStockData(array(
'use_config_manage_stock' => $data[74], //'Use config settings' checkbox
'manage_stock' => $data[73], //manage stock
'is_in_stock' => $data[70], //Stock Availability
)
);
//echo "category id:-".$data[4];echo "<br>----------------<br>";
$cat_name = substr($data[4], strpos($data[4],'/')+strlen('/'));
$category = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('name', $cat_name);
//print_r($category->getData());
$cat_id = $category->getFirstItem()->getEntityId();
$configProduct->setCategoryIds(array(2, 5, $cat_id)); //assign product to categories
/**/
/** assigning associated product to configurable */
/**/
$count_loop = $simple_product_counter;
$config_color_count=0;
$config_size_count=0;
$configurableProductsData=array();
$configurableProductsData_new=array();
$configurableProductsDataSize=array();
$attribute_colorid ="";
for($i=0;$i<$count_loop;$i++)
{
$attributeColorCode = 'color';
$attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
$attribute = $attribute_details->getData();
$attribute_colorid = $attribute['attribute_id'];
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributeColorCode);
if ($attr->usesSource()) { $color_id = $attr->getSource()->getOptionId($simple_product_color[$config_color_count]); }
$current_product_id = Mage::getModel("catalog/product")->getIdBySku( $simple_product_sku[$config_color_count] );
$configurableProductsData[$current_product_id] = array( //['product_id'] = id of a simple product associated with this configurable
'0' => array(
'label' => $simple_product_color[$config_color_count], //attribute label
'attribute_id' => $attribute_colorid, //attribute ID of attribute 'color' in my store
'value_index' => $color_id, //value of 'Green' index of the attribute 'color'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => '0' //value for the pricing
)
);
$config_color_count++;
}
for($i=0;$i<$count_loop;$i++)
{
/*color */
$attributeColorCode = 'color';
$attribute_details_color = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
$attribute_color = $attribute_details_color->getData();
$attribute_colorid = $attribute_color['attribute_id'];
/*---*/
$attributesizeCode = 'size';
$attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributesizeCode);
$attribute = $attribute_details->getData();
$attribute_sizeid = $attribute['attribute_id'];
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributesizeCode);
if ($attr->usesSource()) { $size_id = $attr->getSource()->getOptionId($simple_product_size[$config_size_count]); }
$current_product_id = Mage::getModel("catalog/product")->getIdBySku( $simple_product_sku[$config_size_count] );
$configProduct->getTypeInstance()->setUsedProductAttributeIds(array($attribute_sizeid,$attribute_colorid)); //attribute ID of attribute 'size' in my store
$configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
//$configurableAttributesData[0]['id']=$current_product_id;
//$configurableAttributesData[1]['id']=$current_product_id;
echo "<pre>";print_r($configurableAttributesData);
$configProduct->setCanSaveConfigurableAttributes(true);
$configProduct->setConfigurableAttributesData($configurableAttributesData);
$configurableProductsData_new[$current_product_id] = array( //['920'] = id of a simple product associated with this configurable
'1' => array(
'label' => $simple_product_size[$config_size_count], //attribute label
'attribute_id' => $attribute_sizeid, //attribute ID of attribute 'size' in my store
'value_index' => $size_id, //value of 'Green' index of the attribute 'size'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => '0' //value for the pricing
)
);
$config_size_count++;
}
//echo "<pre>";print_r($configurableProductsData_new);
$configProduct->setConfigurableProductsData($configurableProductsData_new);
//echo "<pre>";print_r($configurableProductsData);
$configProduct->setConfigurableProductsData($configurableProductsData);
$configProduct->save();
$simple_product_counter=0;
unset($simple_product_sku);
unset($simple_product_color);
unset($simple_product_size);
echo 'success<br>';
} catch (Exception $e) {
Mage::log($e->getMessage());
echo $e->getMessage();
}
}
}
fclose($handle);
}
/* #var $indexCollection Mage_Index_Model_Resource_Process_Collection */
/*
$indexCollection = Mage::getModel('index/process')->getCollection();
foreach ($indexCollection as $index) {
$index->reindexAll();
}
*/
?>
I have already done importing product pro grammatically and it is display properly with associated product on admin panel of magneto. Also, I have already done re indexing and clear cache but now, I am fetching problem with display product on frontend. If I am just save and continue edit of associated product of configurable product then after re indexing it is display on frontend. please help me to solve this problem
I have a Wordpress plugin with a file (userinfo.php) that processes a function -- generateUserInfo(). I want to use this function on a sidebar widget. I'm unclear on exactly how to get that done.
Here is the code from userinfo.php inside of my plugin.
require_once("../../../wp-load.php");
//need the current user's ID
$user = get_current_user_id();
$meetings = generateUserInfo($user, 4, 3, 'meetings');
$events = generateUserInfo($user, 6, 2, 'events');
function generateUserInfo($user,$taxonomy_id,$num_required_events,$event_type){
global $wpdb, $table_prefix;
$num_total_events = 0;
$num_actual_events = 0;
//Get the name of the taxonomy term for events (ID: 6)
$events = get_term_by('term_taxonomy_id', $taxonomy_id, 'events_categories');
$event_category_name = $events->name;
$event_posts = get_posts(array('post_type' => 'ai1ec_event', 'events_categories' => $event_category_name, 'posts_per_page' => -1));
foreach($event_posts as $event){
$attended_events_query = $wpdb->get_results("SELECT vote FROM ".$table_prefix."attendance_list WHERE post = " . $event->ID . " AND user = " . $user);
if(count($attended_events_query)>0 && is_array($attended_events_query)) {
foreach($attended_events_query as $evt){
//add to the acutal events attended
if($evt->vote == 1) $num_actual_events++;
}
}
$num_total_events++;
}
$events_msg = '<div>You have attended <br> <span class="big-num">'. $num_actual_events . '</span> / ' . $num_total_events . ' ' . $event_type . '</br>('. $num_required_events.' required)<br><br></div>';
echo $events_msg;
return $events_msg;
}
And here is the beginning of my widget:
function your_widget_display($args) {
extract($args);
echo $before_widget;
echo $before_title . 'Attendance Tracker' . $after_title;
echo $after_widget;
// print some HTML for the widget to display here
echo 'whatever';
}
wp_register_sidebar_widget(
'yac_attendance_widget', // your unique widget id
'YAC Member Attendance Tracker', // widget name
'your_widget_display', // callback function
array( // options
'description' => 'Description of what your widget does'
)
);
Just before echo $after_widget;, add the following
if(function_exists('generateUserInfo')) {
generateUserInfo();
}