How to use agregate Mysql functions with CakePHP - mysql

There is a way to use agregate functions with cakephp? like sum() or avg() with find() method.
UPDATE:
I missed a line in the book
array('fields'=>array('Product.type','MIN(Product.price) as price'), 'group' => 'Product.type');
Showing the basic structure for doing that.
Thanks for the help

In the fields parameter of a find method call, you may pass the field processed by an aggregated function. Example:
$Model->find('all',
array(
'anything' => array(/* */),
'fields' => array(
'SUM (Model.attribute) AS total',
'OTHERFUNCTION(OModel.other_attribute) AS other'
),
'otherthing' => array(/* */)
)
);

In exactly the same way, since CakePHP is just a PHP framework.
<?php
// Make a MySQL Connection
$query = "SELECT type, SUM(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>

Related

Codeigniter query builder using implode function in where_in

Here is my normal sql query using implode function:
SELECT * from search_result WHERE skills IN ('".implode("','",$s_id)."');
Now I want to convert this to codeigniter form. I tried the following code but it fails
$this->db->from('search_result');
$this->db->where_in('skills','".implode("','",$s_id)."');
$query = $this->db->get();
Here is my $s_id array:
Array ( [0] => 2D Design [1] => 3D Design [2] => 3D Modelling )
So anyone please help me to do this. Thanks in advance :)
Official Doc say's
$names = array('Frank', 'Todd', 'James'); # Data Array
$this->db->where_in('username', $names); # passing array
Try like below
Method 01(recommended )
$this->db->from('search_result');
$this->db->where_in('skills',$s_id);
$query = $this->db->get();
Method 02
$this->db->from('search_result');
$this->db->where_in('skills',implode("','",$s_id));
$query = $this->db->get();
Whats wrong on this line
$this->db->where_in('skills','".implode("','",$s_id)."');
don't wrap function with ' or " quotes. Then it will get save as STRING value to DB.
Links
where_in clause in codeigniter.com
You can just write this :
$this->db->from('search_result');
$this->db->where_in('skills', $s_id);
$query = $this->db->get();
Official doc
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

Highstock mysql json compare multiple series

Please help to create a query!
This is a working example of my query Retrieve data as JSON using PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("admin_accounting", $con);
$result = mysql_query("SELECT unix_timestamp(date), sum(ksi2k) FROM accounting where lhc_vo like 'ops' group by year(date), month(date)");
$rows = array();
$rows['type'] = 'area';
$rows['name'] = 'Ops';
while($r = mysql_fetch_array($result)) {
$rows['data'][] = $r[0]*1000;
$rows['data'][] = $r[1];
array_push($rows);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
The JSON results look like this:
{"type":"area","name":"Ops","data":[1167664515000,0,1170342915000,0,1172762115000,0,1175436915000,0,1178028915000,0]}
But I need the JSON results should look like this:
{"type":"area","name":"Ops","data":[[1167664515000,0],[1170342915000,0],[1172762115000,0],[1175436915000,0],[1178028915000,0]]}
I would be very grateful for the help
while($r = mysql_fetch_array($result)) {
$rows['data'][] = array($r[0]*1000, $r[1]);
}
In addition to my other answer, you ought to consider switching away from the ancient (and now deprecated, as of PHP v5.5) ext/mysql. Here is an example using PDO, in which you can see how simple your problem becomes:
<?php
$con = new PDO(
'mysql:hostname=localhost;dbname=admin_accounting',
'user',
'password'
);
$result = $con->query('
SELECT 1000*UNIX_TIMESTAMP(date), SUM(ksi2k)
FROM accounting
WHERE lhc_vo LIKE "ops"
GROUP BY YEAR(date), MONTH(date)
');
print json_encode([
'type' => 'area',
'name' => 'Ops',
'data' => $result->fetchAll(PDO::FETCH_NUM)
]);
?>
Note that:
I have moved the multiplication into the database layer in order that I can simply call fetchAll() to obtain the resulting array;
MySQL will select an indeterminate value from amongst those in each group for the first column in the resultset; should this be undesirable, you will need to apply a suitable aggregate function to the reference to the date column; and
I have used the short array syntax, which is only available from PHP v5.4—if you're using an earlier version, you will need to replace the [ … ] of the argument to json_encode() with array( … ).

Mysql UPDATE syntax, how to use as array

I'm having trouble understanding the documentation for the UPDATE command of MYSQL. I am viewing records in a PHP page from the database and I want to edit them.
To INSERT I have this code which is an array. I want to know if I can do the same with the UPDATE statement, to save me lots of this=$this 's.
Insert
mysql_query("INSERT INTO $tbl_name(title, pbDate, summary, blog) VALUES('$title', 'pbDate', '$summary', '$blog')")or die(mysql_error());
Update
mysql_query("UPDATE $tbl_name SET title='$title', pbDate='$pbDate' summary='$summary' blog='$blog' WHERE id='$id'")
I thinking something like this, but I'm not sure and can't find anything in the manual.
mysql_query("UPDATE $tbl_name SET (title, pbDate, summary, blog) VALUES('$title', 'pbDate', '$summary', '$blog') WHERE id='$id'")
You could use an array ...
Working phpFiddle:
http://phpfiddle.org/main/code/pi9-ckh
<?php
$array = array(
"column" => "some_value",
"title" => "some_title",
);
$setString = '';
foreach($array as $key => $value){
$tempArray[] = $key . ' = ' . "\"" . $value . "\"";
}
$setString = implode(",", $tempArray);
echo $setString;
?>

Magento get all orders numbers shipped as overnight between two dates

Title pretty much describes it, I just need to get all the order numbers
shipped with Overnight shipping between 6-8 to 6-12.
Help appreciated
Here is at least one way of achieving this...
$from = "2012-06-08";
$to = "2012-06-12";
$shippingMethod = "overnight_shipping";
$orderIds = Mage::getResourceModel('sales/order_shipment_collection')
->addAttributeToFilter('created_at', array(
'from' => $from,
'to' => $to,
))
->getColumnValues('order_id')
;
$incrementIds = Mage::getResourceModel('sales/order_collection')
->addAttributeToFilter('shipping_method', array('eq' => $shippingMethod))
->addAttributeToFilter('entity_id', array('in' => $orderIds))
->getColumnValues('increment_id')
;
echo "<ul>";
foreach($incrementIds as $incrementId) {
echo "<li>" . $incrementId . "</li>";
}
echo "</ul>";

How to get all metavalue for a specific custom field for all posts in one category?

I'm trying to get the sum for all the meta values of one custom field. I now get the sum for the metavalues of the whole site. I want it to be restricted to the category you're in.
The code now looks like this:
<?php
$thevariable = $wpdb->get_var($wpdb->prepare("
SELECT SUM($wpdb->postmeta.meta_value)
FROM $wpdb->postmeta, $wpdb->posts
WHERE $wpdb->postmeta.meta_key='mycustomfield'
AND $wpdb->postmeta.post_id=$wpdb->posts.id
"));
echo '<h1>' . $thevariable . '</h1>';
?>
Can somebody help me to filter out one category?
Would be amazing!
M
Inside your WP files, you can add this lines; I guess It will do what you are looking for.
<?php
$MySum = 0;
$args = array(
'category_name' => 'MyCategory',
'meta_key' => 'mycustomfield',
'posts_per_page' => '-1' );
// The Query
$the_query = new WP_Query( $args);
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
$MySum += get_post_meta($post_id, $key, true);
endwhile;
echo '<h1>' . $MySum . '</h1>';
// Reset Post Data
wp_reset_postdata();
?>