magento get product using proudct id - magento

I am trying to get feature product of magento, I am getting all product ids properly in each variables, but its not working inside the loop and shows repeated product.
here is my code
$storeId = Mage::app()->getStore()->getId();
$categoryId = $this->getRequest()->getParam('id', false);
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
$categoryProductTable = $resource->getTableName('catalog/category_product');
//$productEntityIntTable = $resource->getTableName('catalog/product_entity_int'); // doesn't work :(
$productEntityIntTable = (string)Mage::getConfig()->getTablePrefix() . 'catalog_product_entity_int';
$eavAttributeTable = $resource->getTableName('eav/attribute');
$select = $read->select()
->from(array('cp'=>$categoryProductTable))
->join(array('pei'=>$productEntityIntTable), 'pei.entity_id=cp.product_id', array())
->joinNatural(array('ea'=>$eavAttributeTable))
->where('pei.value=1')
->where('ea.attribute_code="featured"');
$_product = $read->fetchAll($select);
$total_product= count($_product);
when i print_r($_product) it shows multiple id of product which are features so its correct
but inside for loop when i try to get product name using id it shows repeated Product names,here is the code
$obj = Mage::getModel('catalog/product');
for($cp=0;$cp <= $total_product; $cp++):
$_product= $obj->load($_product[$cp]['product_id']);
echo $_product->getName();
endfor;

Try this
for($cp=0;$cp <= $total_product; $cp++):
$obj = Mage::getModel('catalog/product');
$_productnew= $obj->load($_product[$cp]['product_id']);
echo $_productnew->getName();
endfor;

Put $obj inside for loop like below,
for($cp=0;$cp <= $total_product; $cp++):
$obj = Mage::getModel('catalog/product');
$_product= $obj->load($_product[$cp]['product_id']);
echo $_product->getName();
endfor;

Related

Get customer ID using Mage::getModel('customer/customer')

I not able to get the customersID am I calling it correctly with Mage::getModel
$customer = Mage::getModel('customer/customer')
->setWebsiteId(2)
->load($this->getRequest()->getParam('customer'));
$customer_id = $customer->getId();
$sku = 'BOX3151';
$sql = "SELECT sfoi.item_id FROM sales_flat_order_item sfoi INNER JOIN sales_flat_order sfo
ON sfo.entity_id = sfoi.order_id WHERE sfo.customer_id = '$customer_id' AND sfoi.sku = '$sku'";
$read_db = Mage::getSingleton('core/resource')->getConnection('core_read');
$result = $read_db->fetchAll($sql);
$total_rows = count($result);
if($total_rows >= 1):
echo ' Found ';
else:
echo ' Empty ';
endif;
endif;
Please check for available data in
$this->getRequest()->getParam('customer')
if you have $customerId there you can use the load() method.
$customer = Mage::getModel('customer/customer')
->setWebsiteId(2)
->load($customerId)
also you can get customer object by $email.
$customer = Mage::getModel('customer/customer')
->setWebsiteId(2)
->loadByEmail($email);
<?php
$email = "customer#gmail.com";
$customer = Mage::getModel("customer/customer")->setWebsiteId(Mage::app()->getWebsite()->getId())->loadByEmail($email);
//use
echo $customer->getId();
echo $customer->getEmail();
echo $customer->getFirstname();
?>

How can i update my products?

I want to update from my script the meta title, the meta description and the meta keywords for all of my products.
The meta title = the name of the product
The meta description = the short description of the product
The meta keywords is the meta keywords i've put from the category of the product.
I can loop and get the informations i want to make the update (except the meta keywords of the description) and after how i can make the update inside the loop ?
Thanks
<?php require_once 'app/Mage.php';
umask(0);
set_time_limit(0); // ignore php timeout
ignore_user_abort(true); // keep on going even if user pulls the plug*
while(ob_get_level())ob_end_clean(); // remove output buffers
ob_implicit_flush(true); // output stuff directly
//error_reporting(E_ALL);
/* not Mage::run(); */
Mage::app('default');
// get product collection (All product)
$storeId = Mage::app()->getStore()->getId();
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->setStoreId($storeId)
->addStoreFilter($storeId);
foreach ($_productCollection as $pro) { // loop each product
$meta_title = $pro['meta_title'];
$meta_description = $pro['meta_description'];
$name = $pro['name'];
$short_description = $pro['short_description'];
// I want to update the meta_title, meta_description, meta_keywords
// meta_description = short_description
// meta_title = name
// meta_keywords = meta keywords from the category of the product
}
?>
You can easy set keyword and description by using standard setters.
Inside foreach loop just use :
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$product->setMetaTitle('Product Title')
->setMetaKeyword('Product keywords')
->setMetaDescription('Product Description')
->save();
endforeach;
Try this,
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$cats = $product->getCategoryIds();
$meta_keys = '';
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($_cat->getMetaKeywords())
$meta_keys .= $_cat->getMetaKeywords().', ';
}
$product->setMetaTitle($pro->getName())
->setMetaKeyword($meta_keys)
->setMetaDescription($pro->getShortDescription())
->save();
endforeach;

Get Random SKU Product Number

I have the following code:
$sku = $id;
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
It works by specfing the SKU id, I want to be able to get random SKU product number and use it so
$sku = random product number from database
I used the following script to generate a random sku from the collection. You can use it to suit your requirement also.
//Geting a random sku from collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$randomSku = $collection->setPage(1, 1)->getFirstItem()->getSKU();
In your case your code should look like.......
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_product = $collection->setPage(1, 1)->getFirstItem()->load();
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
Something like that should work fine ;)
$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$collection->setPage(1, 1);
$_product = $collection->getFirstItem();
Below code I used in project and its working fine for me :
<?php
// get Random prdocut list
$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$numProducts = $this->getNumProducts() ? $this->getNumProducts() : 2;
$collection->setPage(1, $numProducts);
foreach($collection as $product){
echo $product->getName();
}
?>

STRANGE...Not able to get cart items in magento on a custom page (only when the customer is logged in)

Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>
I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}

$item->getProduct()->getQty not working in magento

I wrote a function in shipping.php. I want to get the quantity from each product in the cart. I am using $item->getProduct()->getQty, but this is not working.
Is there any other method?
Have you tried $item->getQty() ?
For future readers: look into the relevant source code, e.g app/code/core/Mage/Sales/Model/Order/ to find the exact API.
In that case, the code you are looking for is probably $item->getQtyOrdered(). Not sure which one you're referring to above.
$cart = Mage::getModel('checkout/cart')->getQuote();
$result = array();
$i = 0;
foreach ($cart->getAllItems() as $item) {
$result[$i]['id'] = $item->getProduct()->getId();
$result[$i]['name'] = $item->getName();
$result[$i]['sku'] = $item->getSku();
$result[$i]['price'] = $item->getPrice();
$result[$i]['qty'] = $item->getQty();
$i++;
}
echo "<pre>";
print_r($result);
Try this.
You can use
$item->getId();
to get the cart product ID too.
$item->getProduct()->getQty; will be returned by NULL;

Resources