get products by user id in magento - magento

How to get user id of magento admin panel, suppose i have created a account in magento admin panel named as user1 and user2 and giving the permission to add a product, then i want to know that user1 entered product and as well as user2 entered product?

After a long try i got the solution.
It worked for me.
$session = Mage::getSingleton('customer/session');
$resource = Mage::getSingleton('core/resource');
$read= $resource->getConnection('core_read');
$event_attending = $resource->getTableName('event_attending');
$select = $read->select('event_id')
->from($event_attending)
->where('user_id = ?',$session->getId())
->order('event_date DESC') ;
$attending_events = $read->fetchAll($select);
$resultArray = '';$str='';
foreach($attending_events as $attEvent){
if($str!='')$str.=',';
$str.=$attEvent['event_id'];
}
//echo $str;
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()){
$events = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addFieldToFilter('entity_id', array('in' => array($str)))
->load();
//print_r($events->toArray());
return $events;
}
else
return '';
}

$user = Mage::getSingleton('admin/session')->getData();
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();
$adminuser = Mage::getSingleton()->getUser();
$roleId = implode('', $adminuser->getRoles());
$userId = $adminuser->getId();

Related

How can I check if user is in usergroup "Friends" in Joomla 3?

how can I check, if current user is in usergroup called for example "Friends" (title) in Joomla 3?
$user = JUser::getInstance($result->id);
$groups = $user->getAuthorisedGroups(); // just IDs, not title
Thanks.
Check this code, I hope it will help you.
$AllGroups = $user->get('groups');
// getting all the groups
foreach($AllGroups as $groupId) {
$user = JFactory::getUser(); // getting user data
$db = JFactory::getDBO();
$userid = $user->get('id'); // logged in user id
$groups = JAccess::getGroupsByUser($userid);
$groupid_list = '(' . implode(',', $groups) . ')';
$query = $db->getQuery(true);
$query->select('id, title');
$query->from('#__usergroups');
$query->where('id IN ' .$groupid_list);
$db->setQuery($query);
$rows = $db->loadRowList();
$grouplist = '';
foreach($rows as $group)
{
if ($groupId == $group[0]) { // checking the logged in user group
$grouplist = $group[1];
}
}
var_dump($grouplist); // it will give you the usergroup name
}
$user = JUser::getInstance($result->id);
$AllGroups = $user->get('groups');
$groupNames = array();
$userid = $user->get('id'); // logged in user id
$groups = JAccess::getGroupsByUser($userid);
$groupid_list = '(' . implode(',', $groups) . ')';
foreach ($AllGroups as $groupId) {
$query = $db->getQuery(true);
$query->select('id, title');
$query->from('#__usergroups');
$query->where('id IN ' . $groupid_list);
$db->setQuery($query);
$rows = $db->loadRowList();
$grouplist = '';
foreach ($rows as $group) {
if ($groupId == $group[0]) { // checking the logged in user group
$grouplist = $group[1];
}
}
array_push($groupNames, $grouplist);
}
$query = $db->getQuery(true)
->select('*')
->from('#__myTable');
if (in_array("Friends", $groupNames)) {
// User is in group "Friends"
}

how I can get all product which i buy

I try write this code
public function allsalesblock(){
echo 'other block ';
$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getId());
->addAttributeToSort('created_at', 'DESC');
$order = Mage::getModel("sales/order")->load($orders); //load order by order id
$ordered_items = $order->getAllItems();
foreach($ordered_items as $item){
echo $item->getItemId(); //product id
echo $item->getSku();
echo $item->getQtyOrdered(); //ordered qty of item
echo $item->getName();
}
}
But this doesn't work - i see white screen. I found this code(and modification) here How can I display all products bought by a customer in magento?
You can get it using below code,
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$email = 'albert#example.com';
$_orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_email',$email);
foreach ($_orders as $order) {
$id[]= $order->getId();
}
//print_r($id);
foreach ($id as $order_id) {
$order = Mage::getModel('sales/order')->load($order_id);
#get all items
$items = $order->getAllItems();
$itemcount= count($items);
$data = array();
$i=0;
#loop for all order items
foreach ($items as $itemId => $item)
{
$data[$i]['name'] = $item->getName();
$data[$i]['price'] = $item->getPrice();
$data[$i]['sku'] = $item->getSku();
$data[$i]['id'] = $item->getProductId();
$data[$i]['qty'] = $item->getQtyToInvoice();
}
#displaying the array in order to see the products
echo '<pre/>';print_r($data);
}
here change the email address as you want to get products which that customer bought,
$email = 'albert#example.com';

Magento - Get customer gender from order query

I have made a query that gets customer's orders. Can I get customer gender based on this query? If not, how can I get customer gender? This is the code I have so far:
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$productId = 297;
$orders = Mage::getModel('sales/order')->getCollection();
$orders
->getSelect()
->joinLeft(
array(
'order_item' =>Mage::getSingleton('core/resource')->getTableName('sales/order_item')),
'order_item.order_id = main_table.entity_id',
array('product_id'=>'product_id'))
->where('product_id=?', $productId)
->group('main_table.entity_id')
->order('main_table.entity_id DESC');
$fields = "date,company,name,country,city,address,postcode,itemname,quantity,price,sku \n";
foreach($orders as $order):
$order->getData();
$order->getIncrementId();
$billingAddress = $order->getBillingAddress();
$shippingAddress = $order->getShippingAddress();
$billingStreet = $billingAddress->getStreet();
$countryCode = $billingAddress->getCountry();
$country = Mage::getModel('directory/country')->loadByCode($countryCode);
$fields .=
date('Y-m-d',strtotime($order->getCreatedAt())).','.
$billingAddress->getCompany().','.
$billingAddress->getName().','.
$country->getName().','.
$billingAddress->getCity().','.
$billingStreet[0].','.
$billingAddress->getPostcode().','.
$order->getShippingDescription() .',';
foreach ($order->getAllItems() as $itemId => $item):
$itemname = $item->getName();
$itemname = str_replace('&', " ", $itemname);
$fields .=
$itemname. ','.
$item->getQtyOrdered().','.
$item->getPrice().','.
$item->getSku().',';
endforeach;
$fields = rtrim($fields, ',');
$fields .= "\n";
endforeach;
$name = date('d-m-Y-H-i-s');
$output = fopen('backend/assets/csv/' . $name . '.csv', 'w');
fwrite ($output,$fields);
fclose ($output);
foreach($orders as $order){
$customer = $order->getCustomer();
Mage::log($customer->getGender());
}
if this does not work then:
foreach($orders as $order){
$customer = $order->getCustomer();
$customerObj = Mage::getModel('customer/customer')->load( $customer->getEntityId());
Mage::log($customerObj->getGender());
}

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();
}

Get ProductName using Collection Magento

I've a list of product Ids and based on that product Id I want to get product Name but as the catalog_product_entity table doesn't contain the product name only sku, I'm trapped.
kindly check my code, I've tried left and right join both but not getting the name
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->getSelect()->joinRight(
array('table_alias'=>'my_table'),
'entity_id = table_alias.product_id',
array('table_alias.*')
);
$result = null;
foreach ($collection as $temp) {
$result[] = array(
'name' => $temp->getCustomer_name(),
);
}
If you want your collection to load the product name, then the first part of your code is right. Here's a simplified version:
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('name');
$result = array();
foreach ($collection as $temp) {
$result[] = array('name' => $temp->getName());
}
this is how I solved it
$resource = Mage::getSingleton('core/resource');
$readResource = $resource->getConnection('core_read');
$tableName = $resource->getTableName('myTable');
$results = $readResource->select('table_alias.*')
->from($tableName)
->joinLeft(
array('table_alias'=>'catalog_product_flat_1'),
'product_id = table_alias.entity_id',
array('table_alias.*')
)->where('customer_id=?',$customerId);
$products=$readResource->fetchAll($results);
$dataList = array();
foreach($products as $row)
{
$dataList[] = array('productName'=>$row['name'],'price'=> $row['price'],'status'=>$row['status'],'myTable_id'=>$row['myTable_id']);
}

Resources