Calculate avrage of mysql result php - php

I want to calculate the avrage of a mysql result in PHP (I'm using CodeIgniter as framework).
My (model) code:
$query = $this->db->query('SELECT stars FROM feedback');
$res = $query->result_array();
$avrage = array_sum($res); // The impossible part
$avrage = round($avrage,0);
The result of the query looks like this: (print_r) Array ( [0] => Array ( [stars] => 5 ) [1] => Array ( [stars] => 3 ) )
I just want the '5' and '3' in a separate array, so array_sum() can do it's job. How do I do this?
Thanks.

You can do it in SQL directly using AVG()
SELECT avg(stars) as avg_stars
FROM feedback

Why not use AVG directly in your query?
'SELECT AVG(stars) as average FROM feedback'

The best way to do this would be to modify your SQL query, like this: SELECT AVG(stars) as stars_average FROM feedback. Then, after fetching the result set, you can do the following in your PHP code: $average = $res[0]['stars_average'];.

Related

How to make Laravel whereIn not sorted automatically

my array from $temp is Array ( [0] => 22 [1] => 26 [2] => 20 [3] => 24 ) or 22|26|20|24
when I use whereIn like this
$robjeks = DB::table('objek')->whereIn('id', $temp)->get();
the result is 20|22|24|26|
it's automatically sorted. I want it's not sorted.
how to make it same like 22|26|20|24?
thanks for your attention.
This has nothing to do with Laravel. Read here first: avoid Sorting by the MYSQL IN Keyword
Then, to do this, you can use this code:
$temp = [22, 26, 20, 24];
$tempStr = implode(',', $temp);
$robjeks = DB::table('objek')
->whereIn('id', $temp)
->orderByRaw(DB::raw("FIELD(id, $tempStr)"))
->get();
You might be in risk with sql injection in this case, so please sanitize the array of numbers accordingly.
Ref: Laravel: order by where in
I think it has more to do with SQL rather than Laravel. If you are using autoincrement id, then obviously 22 is found before 26. If you want to change that you may follow this link:
Laravel: order by where in
Or manually order your query yourself. eg.: ->orderBy('name') or something else.

Associative array from a database with codeigniter

On my models I try to write a php model that will get me a associative array from a database. But I don't quite know how to approach this.
So after I execute this SQL query:
SELECT balance_events.weight,balance_events.added_date,
balance_entries.mid FROM balance_events, balance_entries
WHERE balance_entries.added_date BETWEEN '2016-08-02' AND '2016-08-03'
AND balance_entries.ptid =12
AND balance_entries.beid = balance_events.id
I will get this table:
And from that table I want to extract a asociative array that it will look like this:
count = ['13'=>1, '6'=>4, '16'=>3, '4'=>3]
where 'mid'=>number of how many times that mid can be found in the table.
ex. mid '13'=>1 cause you can found it only once.
I think that I will have to use SQL COUNT function, but how I can aggregate all of this in a PHP model in codeigniter? I know how to configure controller and view, but I don't know how to actually do the actual php model that will get me the desired array.
Try this query may help you ,
$result = $this->db->select('balance_events.weight,balance_events.added_date,COUNT(balance_entries.mid) as mid_count')
->from('balance_events, balance_entries')
->where('balance_entries.added_date BETWEEN "2016-08-02" AND "2016-08-03" ')
->where('balance_entries.ptid','12')
->where('balance_entries.beid','balance_events.id')
->group_by('balance_entries.mid')
->get();
return $result->result_array();
I'm not sure how you would create this in SQL but since you tagged php, I wrote a function that would do just this.
<?php
$query = array(array("mid"=>13), array("mid"=>2), array("mid"=>13), array("mid" =>6), array("mid" => 13), array("mid" => 6));
function createMidArray($queryResult){
$returnArray = array();
foreach ($queryResult as $qr){
$returnArray[$qr['mid']]++;
}
return $returnArray;
}
print_r(createMidArray($query));
?>
The output of this was Array ( [13] => 3 [2] => 1 [6] => 2 ) which matches up to my inputted $query (which is a 2D array). I'm expecting the output of your query is stored in a similar array, but with more data and keys

MySQL to PHP Array

Can you please help me extracting MySQL data in php array.
my sql:
SELECT count(*) as total, post_type as type FROM wp_posts group by post_type;
to php, like below:
<?php $total = array(5,7, .. , ..); $type = array('Page', 'Post', '..',..'); ?>
Array should come from database
Thanks :)
You can't get two separate arrays from single SQL query either you have to run the mysql query two times or Write a PHP code which gives you the desired result.
Your current query will give result as follow.
Array
(
[0] => Array
(
[total] => 5
[post_type] => Page
)
)
Now you have to traverse these array to create two separate arrays you want.
$total=array_column($result,'total');
$type = array_column($result,'post_type');
Above code will give you two separate arrays.
Thanks to Niet the Dark Absol for array_column, it looks more clean then traversing manually.

Access value in result set row where the value comes from a MySQL function call

So as normal PHP query returns an array it's never been explained to me how you actually extract the value from the query's result set array when the column value is the return value of a MySQL function call.
$countThemes = Singlequery(
'SELECT COUNT(1) FROM items WHERE type = :type',
array(':type' => 'theme'),
$conn
);
This is my query and it returns;
Array
(
[0] => Array
(
[COUNT(1)] => 5
)
)
I need the value 5. So far I've setup this below but I'm not sure what to call because I can't call a column name like a normal Select * query.
<?php foreach ($countThemes as $countTheme) : ?>
View All <?= $countTheme['name']; ?>
<?php endforeach; ?>
Use an alias for the return of the COUNT function:
$countThemes = Singlequery('SELECT COUNT(1) AS num_items FROM items WHERE type = :type',
array(':type' => 'theme'), $conn);
Then, your array should have the index num_items instead of COUNT(1).
This will also work :
echo $result[0]['COUNT(1)'];
However, using an alias in the SQL query - as suggested by nickb - is more elegant in my opinion.

How to insert records using select active records in codeigniter

I found some questions same with this issue but i can't seem to find a right answer for my own code. so i'm going to post my problem.
my code is not working and posting errors. like "stdClass could not be converted to string" or problem regarding to array.
here's my code in model
$this->db->select("*");
$this->db->from("table1");
$query = $this->db->get();
$this->db->insert("table2", $query->result());
this is not working.
now when i use print_r($query) the result is this.
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #40 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => )
Try this:
If you select('*') it will return many rows, so it is not advisable to use insert()
since insert will only process ONE ROW
try using insert_batch()
$this->db->insert_batch("table2", $query->result());
//or
$this->db->insert_batch("table2", $query->result_array());
If you need to use insert() you must put a limit(1) to your first query.
Or you have to catch your query if it returns many rows
$numrows = $query->num_rows();
if($numrows == 1)
{
$this->db->insert("table2", $query->row());
}elseif($numrows > 1){
$this->db->insert_batch("table2", $query->result_array());
}
I suspect $query is coming back as an object.
Try one of the following, in place of your last line with $query->result():
$this->db->insert("table2", $query->row());
//or
$this->db->insert("table2", $query->result_array());
If all you want to achieve is copying data between two tables you should try this query
INSERT INTO to_table (field1,field2) (SELECT field1,field2 FROM from_table);
This is more efficient in a lot of ways.
It produces the result in a single query.
No data is brought into or sent from the application resulting in huge speed benefit.

Categories