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');
Related
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);
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.
I am trying to group my results by date. My date field is a mySQL timestamp and I am using Laravel 4.1. For the purpose of this, I am using a field named 'start_time' and need it to group literally by date only, disregarding the actual time.
Can anyone point me in the right direction? I am unfamiliar with using dates like this in this framework.
$agenda = Agenda::where('active', '=', 'Y');
$agenda->with('user');
$agenda->with('room');
$agenda->groupBy(DB::raw('DATE_FORMAT(start_time, "%d/%m/%Y")'));
$agenda->orderBy('start_time', 'asc');
$agenda->distinct();
$agenda->get();
return View::make('agenda')->with('agendas', $agenda);
#foreach($agendas as $agenda)
{{ date("d M Y",strtotime($agenda->start_time)) }}
#endforeach
This may be a very basic approach but that's how I always do it:
<?php $currentDate = null ?>
#foreach($agendas as $agenda)
<?php $date = date("d M Y",strtotime($agenda->start_time)); ?>
#if($currentDate != $date)
<?php $currentDate = $date; ?>
<h3>{{ $date }}</h3>
#endif
{{-- do the stuff --}}
#endforeach
It would be nice (and best/better practice) not to do the date formatting like this in the view. But you get the idea.
May be you would split to more foreach loop (?) .
At first, we will query to get all of start_time with distinct, order, eta...
Then, push a foreach loop to get data belonged to each start_time element.
Hope this will be usefull.
I would like to ask you for piece of information that would help me to resolve my issue.
My purpose is to get from the Magento database particular product qty in every order (orders must be in exact definied status). I use batch/script standing apart from Magento but uses Mage:app. I do not know if I should start with models (which seems to be logical approach but slow in the same time) or to work directly on database (which is more difficult).
Thank you for any advice.
Regards,
Querying the database is not that complicated:
SELECT *
FROM sales_flat_order o
LEFT JOIN sales_flat_order_item i ON o.entity_id = i.order_id
WHERE o.status IN ('pending', 'processing')
AND i.product_id = <YOUR_PRODUCT_ID>
total_qty_ordered field in result will represent the ordered quantity.
Getting ordered items quantity through models is not heavy either:
<?php
require_once('app/Mage.php');
umask(0);
Mage::app('default');
$core_resource = Mage::getSingleton('core/resource');
$orders = Mage::getResourceModel('sales/order_collection');
$orders->getSelect()->joinLeft(array('ordered_products' => $core_resource->getTableName('sales/order_item')), 'main_table.entity_id = ordered_products.order_id', array('ordered_products.*'));
$orders->addAttributeToSelect('*')
->addFieldToFilter('status', array('in' => array('pending', 'processing')))
->addAttributeToFilter('main_table.store_id', Mage::app()->getStore()->getId())
->addAttributeToFilter('ordered_products.product_id', array('eq' => '2'));
foreach($orders as $order) {
echo 'Order #' . $order->getId() . ': ' . $order->getData('total_qty_ordered') . '<br/>';
}
The first approach may be a faster but the second one will be Magneto-Upgrade-Safe. So you decide which approach to use.
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>
";
}