Get number of swatches of an attribute that has a product - magento-1.9

I have configurable products with a swatch attribute, in this case is color.
I need to know how many colors (the number) has a product, or maybe how many single products compose this configurable product.
As a matter of fact, I need to know when there is more than one color in a product.

Finally I found it, maybe it will help somebody in the future:
$productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);
//in this case the attribute color that I needed is in [0] position
$available_colors = sizeof($productAttributeOptions[0]["values"]);
if ($available_colors >1):
//custom code
endif;
Edit: This solution works for one product, or at least for a few products, but if you need it in a list of products it is really slow to run this code in each of the products. Sometimes it drives to a timeout and closes the db connections, so the web crashes with an error.
Finally I got a solution, maybe it is not the best one, but it is pretty fast compared to the one I was using before:
$_idsForTheQuery = $_productCollection->getAllIds();
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql_query = "SELECT parent_id, COUNT(parent_id) AS colors FROM
(SELECT cpr.parent_id FROM `eav_attribute` a
LEFT JOIN `catalog_product_entity_int` cpei ON cpei.attribute_id=a.attribute_id
LEFT JOIN `catalog_product_relation` cpr ON cpr.child_id=cpei.entity_id
WHERE attribute_code = 'color' AND cpr.parent_id IN (".implode (", ", $_idsForTheQuery).")
GROUP BY cpr.parent_id, cpei.value) colors
GROUP BY parent_id";
$results = $read->query($sql_query);
$number_of_colors_by_id_array = array();
foreach($results as $r)
{
$number_of_colors_by_id_array[$r["parent_id"]] = $r["colors"];
}
and then in the foreach loop of the products
<?php if ($number_of_colors_by_id_array[$_product->getId()]>1): ?>
<div class="aditional-colors-message">
<?php echo __('more colors available'); ?>
</div>
<?php endif; ?>

Related

How to add pagination for wishlist products in magento 1.9

I am trying to get products on the page-wise for wishlist collection. I was getting a count for product collections in the below code. I have set the page size to one but it's showing the product count two. Please help me to fix this. Thanks.
$wishlist1 = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true)
->setCurPage($page_num)
->setPageSize(1)
->load();
foreach($wishlist1->getItemCollection() as $product){
$_product = Mage::getModel('catalog/product')->load($product['product_id']);//product id here
echo $product['product_id'];
}
Please try with this code:
<?php
$customer = Mage::getModel("customer/customer")->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail('mohit#streammarket.co.uk');
$wishlistItems = Mage::getModel('wishlist/item')->getCollection()
->setWebsiteId($customer->getWebsiteId())
->setCustomerGroupId($customer->getGroupId())
->setCurPage(1)
->setPageSize(1)
->load();
?>

Pull SKU, Manufacturer and custom attribute from Magento database

I'm trying to pull a full list of products from the database with the SKU, manufacturer and a custom attribute called 'GTIN'.
I'm really struggling with the custom attribute part.
This statement works to pull the manufacturer and SKU
SELECT cpe.sku, m1.manufacturer,
FROM catalog_product_entity AS cpe
INNER JOIN exportview_manufacturer AS m1 ON cpe.entity_id = m1.entity_id
My MySQL is very poor and I can't seem to get this custom attribute. I've found the following statement online which I KNOW has all the details I need to make this work but thus far I've been getting my head in a mess trying to implement it
SELECT e.entity_id AS product_id, var.value AS product_name
FROM catalog_product_entity e, eav_attribute eav, catalog_product_entity_varchar var
WHERE
e.entity_type_id = eav.entity_type_id
AND eav.attribute_code = 'gtin'
AND eav.attribute_id = var.attribute_id
AND var.entity_id = e.entity_id
I simply need the first statement to also include the 'gtin' column, but joining is where I'm falling short. Can someone please assist?
You need to create one PHP script to get all product and it's attribute. So first create all_product.php file on your Magento root and add below code.
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../app/Mage.php';
Mage::app();
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*') // select all attributes
->setPageSize(5000) // limit number of results returned
->setCurPage(1); // set the offset (useful for pagination)
foreach ($collection as $product) {
echo $product->getName(); //get name
/*you can get any attribue you want like name above. Even you can get all custom attribule for product for that you need to use print_r($collection->getData()) above foreach*/
}
Hope it will work.

How to make like and unlike

I have tried to make like and like system using ajax and mysql.
Click like, like is added and Click again, like min 1.
I want, when I click unlike, it will back to like.
But this, unlike until minus..
This is my mysql
<?php
include 'connect.php';
session_start();
$ip=$_SESSION['id'];
if ($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysql_query("select id_user from social where track_id='$id' and id_user='$ip'");
$count=mysql_num_rows($ip_sql);
if ($count==0)
{
$sql = "update track set jumlah_like=jumlah_like+1 where track_id='$id'";
mysql_query($sql);
$sql_in = "insert into social (id_user,track_id) values ('$ip','$id')";
mysql_query($sql_in);
$result=mysql_query("select jumlah_like from track where track_id='$id'");
$row=mysql_fetch_array($result);
$love=$row['jumlah_like'];
?>
<span class="broke_love" align="left"><?php echo $love; ?></span>
<?php
}
else
{
$sql = "update track set jumlah_like=jumlah_like-1 where track_id='$id'";
mysql_query($sql);
//$sql_in = "insert into social (id_user,track_id) values ('$ip','$id')";
//mysql_query($sql_in);
$result=mysql_query("select jumlah_like from track where track_id='$id'");
$row=mysql_fetch_array($result);
$love=$row['jumlah_like'];
echo "<span class=on_img align=left>$love</span>";
}
}
?>
The problem is algorithmic that is causing your button to be stuck on 'unlike'.
Your basic condition is: if ($count==0) which always returns greater than 0 after the statement $sql_in = "insert into social (id_user,track_id) values ('$ip','$id')"; is run.
Therefore, your code gets stuck in always executing the else, and continously diminishing the likes.
You need to change your logic to be more:
Check if likes exist and add for specific user.
If like already exists, remove like record.
I think you are missing something from your script as you do not appear to remove a record from the table social.
However most of your selects and updates can be done with a single piece of SQL. Something
like:-
UPDATE track a
LEFT OUTER JOIN social b ON a.track_id = b.track_id AND id_user='$ip'
SET a.jumlah_like = a.jumlah_like + IF(b.track_id IS NULL, 1, -1)
It would probably be better to have a votes table rather than adding and deleting records on the social table. One row per vote.

MySQL question: Appending text to a wordpress post, but only if it's in a certain category

I need to amend (via CONCAT, presumably) something to every wordpress post if it belongs to a certain category (say, category ID 7), but I'm struggling to get it to work.
To test, I'm first trying to select all the relevant posts. So far, I have the following:
SELECT post_title
FROM cruise_wp_posts
LEFT JOIN cruise_wp_term_relationships
ON cruise_wp_term_relationships.object_id = cruise_wp_posts.ID
WHERE term_taxonomy_id = 87;
However, it only lists posts that are only in category 87 - I need all posts that are in category 87 (and possibly other categories too)
I'm a MySQL newbie, and this is really breaking my brain.
Any pointers would be passionately welcomed.
The best way to do it is to filter it in as needed. This way the addition is made everywhere the_content is used and not just in the templates you modify.
<?php
function my_content_concat($the_content) {
if (in_category(7)) {
$the_content .= '<br /><br />foo!';
}
return $the_content;
}
add_filter('the_content', 'my_content_concat', 9);
?>
in_category can take the id, name or slug of your target category.
I put the filter at 9 so that it runs before WordPress texturizes the content. If you don't need that run it at 11.
Why not just use get_the_category( $id ) and ammend the text when you output the post?
$cat = get_the_category( $postID );
if ($cat == 7) {
//Add text here
}

PHP Array Duplicates

my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
What I would like to do is display each user individually, and count the number of contacts each user has. I had a look at the post "How to detect duplicate posts in PHP array, which helped a bit, but I am still stuck.
Please see my code for the query below, I have left out the array duplicate part as it is a pretty mess at the moment.
<?php
$result = mysql_query("SELECT * FROM vines");
while($row = mysql_fetch_array($result)) {
$results=$row['vinename'];
echo $results;
echo "<br />";
}
?>
This result returns the below, obviously these are records from the vinename coloumn.
Marks Vine<br />
Marks Vine<br />
Marks Vine<br />
Tasch Vine<br />
Tasch Vine<br />
Regards
Mark Loxton
Hi there, my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
You can do this in the query itself a lot more easily than in the PHP code afterwards.
SELECT name, COUNT(id) AS count FROM vines GROUP BY name
Just change the SQL Query to
SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename
and then do
echo $row['vinename']." #".$row['counter']."<br />";
I would run two types queries...
1) Select each UNIQUE user from vines.
2) For each user in that set, run a second COUNT query against that user's id in the table "vines".
I hope that helps.
You can create a separate array to store records you've already output there.
<?php
$result = mysql_query("SELECT * FROM vines");
$duplicates = array(); ## store duplcated names here
while($row = mysql_fetch_array($result)) {
$results = $row['vinename'];
if (!array_key_exists($results, $duplicates)) {
echo $results;
echo "<br />";
$duplicates[$results] = 1; ## mark that we've already output this records
}
}
?>
You can try, change your query to use count and group of SQL.
Somoe thing like
$result = mysql_query("SELECT count(*) as total,name FROM vines GROUP by name");
firstly thank you everyone for such awesome input. I seriously did not expect such a quick response. I am seriously grateful.
I used the recommendation from Jitter. I have pretty much been going through so many variations of the above code today, but just needed that missing piece.
Thanks, everyone. Below is what the final code looks like for anyone else who has the same problem in the future.
<?php
$result = mysql_query("SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename ORDER BY counter DESC LIMIT 0, 3");
while($vinerow = mysql_fetch_array($result))
echo $vinerow['vinename']." has ".$vinerow['counter']." tomatos."."<br />";
?>
change your query to:
SELECT distinct * FROM vines