Magento files: where to paste and read results of this query - magento

I am giving up on trying to fetch values for all product attributes on magento by SQL as it gets a nightmare of joins, yet, I am not familiar with the folders structure and I dont know where to paste this query below. Could anyone give me a handguided enumeration on where to go please? If possible I d like to have more values, like description, meta keywords etc
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$collection = Mage::getModel('catalog/product')->getCollection();
echo '<table border="1"> ';
echo '<tr>';
echo "<th>entity_id <th />";
echo "<th>store_id <th />";
echo "<th>name<th />";
echo "<th>sku <th />";
echo "<th>price<th />";
echo "<th>status<th />";
echo '</tr>';
foreach ($collection as $product_all) {
$sku = $product_all['sku'];
$product_id = $product_all['entity_id'];
// call product model and create product object
$product = Mage::getModel('catalog/product')->load($product_id);
$pk_sku = $product['sku'];
$pk_name = $product['name'];
$store_id = $product->getStoreIds();
$pk_price = $product['price'];
$status = $product->getStatus();
echo '<tr>';
echo "<td>".$product_id."<td />";
echo "<td>".$store_id[0]."<td />";
echo "<td>".$pk_name."<td />";
echo "<td>".$pk_sku."<td />";
echo "<td>".$pk_price."<td />";
echo "<td>".$status."<td />";
echo '</tr>';
}
echo '</table>';?>

If you want to see product attribute data, these are the tables in the db you need to concern yourself with.
catalog_product_entity: stores all base product data
eav_attribute: lists all attribute_codes and the attribute type
catalog_product_entity_{varchar/int/datetime/..}: contains relevant attribute values based on eav_attribute attribute_id and catalog_product_entity entity_id.
So if you wanted to use a SQL query to get a certain attribute, you could use a statement like this to view all varchar attributes stored for a particular product (or all products):
SELECT cpe.entity_id, cpe.sku, attrib.attribute_id, attrib.value
FROM catalog_product_entity AS cpe
LEFT JOIN (
SELECT entity_id, attribute_id, VALUE
FROM catalog_product_entity_varchar AS attrib
) AS attrib ON cpe.entity_id = attrib.entity_id
WHERE cpe.sku = '{your sku here}';
With these tables and a little more research into the eav system and a little sql knowledge, you should be able to wrap your head around how the system works and see the data you need.

Related

Codeigniter update_batch in Core PHP

everyone.
In the codeigniter there is update_batch function by using it we are able to bulk update multiple rows.
$this->db->update_batch('table_name', $update_data_array, 'where_condition_field_name');
I want similar functionality in core PHP in one function or in one file. Is there any workaround?
Is there any way to extract update_batch function from Codeigniter in one file/function?
I tried to extract this function but it is very lengthy process and there will be many files / functions should be extracted.
Please help me in this regard
Thanks in advance
You can also insert multiple rows into a database table with a single insert query in core php.
(1)One Way
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}
$sql = "INSERT INTO mytable (first_name, last_name, age)
VALUES('raj', 'sharma', '15'),
('kapil', 'verma', '42'),
('monty', 'singh', '29'),
('arjun', 'patel', '32') ";
if ($mysqli->query($sql) == = true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
? >
(2)Second Way
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your sql query like this:-
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
You can easily construct similar type of query using PHP.
Lets use array containing key value pair and implode statement to generate query.
Here’s the snippet.
<?php
$coupons = array(
1 => 'val1',
2 => 'va2',
3 => 'val3',
);
$data = array();
foreach ($coupons AS $key => $value) {
$data[] = "($key, '$value')";
}
$query = "INSERT INTO `tbl_update` (id, val) VALUES " . implode(', ', $data) . " ON DUPLICATE KEY UPDATE val = VALUES(val)";
$this->db->query($query);
?>
Alternatively, you can use CASE construct in UPDATE statement. Then the query would be something
like:
UPDATE tbl_coupons
SET code = (CASE id WHEN 1 THEN 'ABCDE'
WHEN 2 THEN 'GHIJK'
WHEN 3 THEN 'EFGHI'
END)
WHERE id IN(1, 2 ,3);

loop through joined tables in codeigniter

For some time I have struggled with what I think should be a simple display of a joined result. My code is as follows.
<h1>start test</h1>
<?php
ee()->db->from('store_orders as so');
ee()->db->join('store_order_items as si', 'so.id = si.order_id', 'inner');
$query = ee()->db->get();
echo '<h1>This is a list of all the channel titles999</h1>';
?>
<ul>
<?php
// print_r($query->result());
foreach($query->result() as $row)
{
echo '<li>' . $row->id . ' - ' . $row->order_id . ' - ' . date('m/d/Y:G:i:s', strtotime($row->order_date)) . '</li>';
}
?>
</ul>
In the foreach loop I want to display the results of the join to make sure that the order id is equal across the 2 tables.....it is not.
I've tried inner, outer, left and right on the join, each giving different results but never what I think should be the correct result...both fields should be the same.
Any help or insight would be appreciated.
BTY, I model my query in MS Access to get my basic syntax.
Thanks
Anthony Jaxon, Los Angeles, CA USA
Because you do a SELECT * and both table have a field called "id", MySQL doesn't know which one you want.
You need to set an aliase to your fields
ee()->db->select('so.id, si.order_id, so.order_date');
ee()->db->join('store_order_items si', 'so.id = si.order_id');
$query = ee()->db->get('store_orders so');

NextGen Plugin - Display Gallery Image Count

I am using the NextGen gallery WordPress plugin for a site. In my gallery.php template I want to retrieve the number of images for each gallery displayed in the loop. I cannot figure out a way to get the data and print it under the thumbnail of each gallery that's called in gallery.php
Here is where I want to insert the gallery image count and print it:
<a rel="prettyPhoto" href="<?php echo $image->imageURL ?>"
<?php $image->thumbcode ?>><span>view</span></a> <?php echo $total_images; ?> pictures
Anybody have any tips?
Thanks,
Ian
I used this little hack to get my gallery id from the shortcode I pasted inside my post ([nggallery=1])
<?php
$id = get_the_ID();//Get the id of the specific post (inside the loop)
$string = get_the_content();//You get the whole post content where in the end of it lies your shortcode (for example [nggallery=1])
if(preg_match_all('/=(.*?)\]/s',$string,$match)) {
$finalstring=$match[1][0];
}// get the id only (gets all chars after '=' and before ']')
global $wpdb;
$total_attachments = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures WHERE galleryid=$finalstring" ); // Voila!
?>
Hope my solution can work for you.
This is the code you need to count the images:
$global $wpdb;
$images = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures") );
$galleries = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggallery") );
$albums = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggalbum") );
The answer is you can't.
You can count the keys in the $images variable but it will return the wrong number.
You can retrieve the total number of all the images, or all the galleries which is useless.
You can even use a counter as you cycle through the array to try to count how many images are in your gallery, but you'll still get the wrong number.
You can try to use the global variables tthere by default: images->total, which are empty and undefined and don't even exist in the $images or $current object.
The code displays a ("Picture 3 of 7)" type display. If you use it in the imagebrowser.php template, it works. If you paste this exact same code in the gallery-carousel.php template. It will not work. Now you might think switching to $current->total would work, since it inexplicably does for the rest of the variables when using gallery_carousel, but no, it does not. The answer is you have to pull the info from the database directly.
<?php _e('Picture', 'nggallery') ?> <?php echo $image->number ?> <?php _e('of', 'nggallery')?> <?php echo $image->total ?>
It is a sinister, sinister plugin.
If you can't count the images on a gallery, you can count the tags on html block.
On my theme, I get the gallery ID from an custom field and echo the gallery inside the template. So, it's something like that:
<?php
$myGalleryId = 1; // example
$displayImages = 0; // the number of images you want to display from gallery. 0 = all images
$newnggShortcodes = new NextGEN_Shortcodes;
$htmlGallery = str_get_html($newnggShortcodes->show_gallery( array("id"=>$myGalleryId,"images"=>$displayImages,"template"=>"popular") ));
$countImg = count($htmlGallery->find('img')); // number of total <img> tags inside the gallery
$str = $htmlGallery;
?>
<!-- now the html -->
<div id="myGallery">
<?php echo $str; ?>
</div>
<span>Total images: <?php echo $countImg; ?></span>
Hope it helps.

PHP - How to accomplish this if?

I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}

attribute select magento query

i am trying to get this query in magento.
Select merk, option_id from catalog ....... group by option_id
Sofar i have this but it aint showing the option_id value unfortunately and also i dont know how to group by them...
i hope someone is willing to help me
[code]
<?php
function getMenuWatches(){
$collection = Mage::getModel("catalog/product")->getCollection();
$collection->addAttributeToFilter("attribute_set_id", 26);
$collection->addAttributeToSelect("option_id , merk");
return $collection;
}
$collection=getMenuWatches();
//print_r($collection);
foreach ($collection as $product){
echo $product->getOptionId();
$product->getMerk();
echo $product->getId('merk');
echo $product->getAttributeText('merk')."<br/>";
}
?>
[/code]
$collection->addAttributeToSelect(array('option_id', 'merk'));
$collection->groupByAttribute('option_id');
Attributes with multiple choices are stored as comma separated values.
So you just need add "merk" attribute in select object:
$collection->addAttributeToSelect('merk');
and when you are iterating the collection, you may retrieve options id by calling your attribute value:
// List of option_id values
$values = explode(',', $product->getMerk());
After retrieving of the values you need to retrieve option label for each option id
$attribute = $product->getResource()->getAttribute('merk');
$optionLabel = $attribute->getSource()->getOptionText($optionId);
To filter by one of the multiple values you may use:
// Creates FIND_IN_SET statement for comma-separated attribute values
$collection->addAttributeToFilter('merk', array('finset' => $optionId));

Resources