Count row divided by count row - php

I have some problem with MySQL syntax in CI this is my table
id_data | nama_depan | nama_belakang | gender | luas_lantai | jenis_lantai
| status
I already tried code bellow and show error
Message: Object of class CI_DB_mysqli_result could not be converted to
int
public function getStatus1($status){
$str = "SELECT count(status)
FROM data_latih WHERE status = 1 ";
$str1 = "SELECT count(status)
FROM data_latih ";
$query = $this->db->query($str);
$query1 = $this->db->query($str1);
return $query / $query1;
}
expected output is decimal number of count status = 1 divided by count all rows
EDIT : Found the answer, thank you so much guys i'm new in programming so bear with me :)))

The problem is that you are trying to divide an Object by the Object which does not make any sense, Try this CI way,
public function getStatus1($status){
$this->db->count_all_results('data_latih ');
$this->db->where('status ', '1');
$this->db->from('data_latih ');
$result1 = (float)$this->db->count_all_results();
$result2 = (float)$this->db->count_all('data_latih');
return $result1 / $result2 ;
}

You can actually handle this with a single query:
SELECT
SUM(status = 1) / COUNT(status) AS result
FROM data_latih;
Regarding your PHP code, I would recommend assigning aliases to the various counts, and then accessing those aliases.
$sql = "SELECT SUM(status = 1) / COUNT(status) AS result FROM data_latih";
$result = $this->db->query($sql);
if ($row = $result->fetch_array()) {
echo $row['result'];
}

Related

Sum fields from different tables per userID

Need your help.
php, mysql
I have the following project.
I have two tables
**table 1**
user_id Plan
1 5
1 7
2 5
2 9
3 7
1 9
**table 2**
Plan Price
5 100
7 200
9 300
I must find the total cost of plans selected by one user
eg user_id = 2 must pay 400
I have already the following code, but this one adds the Price of all Plans in database in the above example total cost = 600
What am I doing wrong? :(
$totalcost = NULL;
$sql = "select SUM(Plan.Cost) as ANSWER FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$totalcost = mysql_fetch_row($result);
$sql = "select * FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$rows = mysql_num_rows($result);
$Plan = array();
if (is_resource($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$Plan[] = $row;
}
}
You have to specify the user_id in your query, like:
$user_id = 2; // or get it from $_GET, $_POST...
$sql = "select SUM(Plan.Cost) as ANSWER
FROM Plan, Users
WHERE Users.Plan = Plan.Plan AND Users.user_id = $user_id";
You probably want to use LEFT JOIN in your query, so you can make something like this:
SELECT table1.user_id, table1.plan, SUM(table2.cost) FROM table1 LEFT JOIN table2 ON table1.plan=table2.plan WHERE table1.user_id = $user_id;
this way you can fetch results in 1 query and make database do all the work instead of looping through data in functions etc.
SQL left join tutorial

Identify change in job code from a mySQL table

I am working with a very large table in MySQL containing employee information collected over the last four years. I want to know if someone's job code changed between that time, and if so, push their data into an array for json encoding in php.
An example of the data looks like this:
Year Emp ID Job Code
2015 1234 X908
2014 1234 X908
2013 1234 X908
**2015 5421 Y444**
2014 5421 Z900
2013 5421 Z900
For employee 1234 there has been no job change between 2013-2015; I would however like to catch employee 5421 whose job code changed between 2014 and 2015.
So far, I have written a script in PHP without good results.
$query = mysqli_query("SELECT year, emp_id, job_code from big_table ");
$rows = array();
while ($r = mysql_fetch_assoc($query)) {
if ($r['emp_id'] == $r['emp_id'] and $r['job_code'] != $r['job_code']) {
$rows[] = $r;
}
echo json_encode($rows);
Thank you in advance for your help!
You can get the required data in the SQL query without having to pull all user records into PHP. This will be significantly more efficient than processing the data in PHP.
You can get the job code count for each user:
SELECT emp_id, COUNT(DISTINCT job_code) AS diffjobs FROM big_table GROUP BY emp_id
Then you can conditionally get users with more than 1 distinct job code by wrapping it in a subquery:
SELECT emp_id, diffjobs FROM
(SELECT emp_id, COUNT(DISTINCT job_code) AS diffjobs FROM big_table GROUP BY emp_id) d
WHERE diffjobs > 1
This loop should work:
$rows = array();
$jobChanges = array();
while ($r = mysql_fetch_assoc($query)) {
if (!isset($rows[$r['emp_id']])){
$rows[$r['emp_id']] = $r;
} elseif ($rows[$r['emp_id']]['job_code'] != $r['job_code']) {
// Handle differing job_code...
if (!isset($jobChanges[$r['emp_id'])) {
$jobChanges[$r[emp_id]] = array();
}
// Keep track of all differing job codes per emp_id
// I am not going to go any further than that...
$jobChanges[$r[emp_id]][] = $r;
}
}
You can get the desired employees whose job has changed in between years using GROUP BY and HAVING clause, like this:
$query = mysqli_query($link, "SELECT emp_id from big_table GROUP BY emp_id HAVING COUNT(DISTINCT job_code) > 1");
$rows = array();
while ($r = mysqli_fetch_assoc($query)){
$rows[] = $r;
}
echo json_encode($rows);
Caution: Don't mix mysqli and mysql database extensions in your code.
This can be done with a JOIN query in MySQL, so that you only return the rows that have changed from the previous year -
SELECT
a.year, a.emp_id, a.job_code,
b.year prev_year, b.job_code prev_job_code
FROM big_table a
JOIN big_table b
ON a.emp_id = b.emp_id
AND b.year = a.year-1
WHERE a.job_code != b.job_code
see this SQLFiddle - http://sqlfiddle.com/#!9/95e680/10
so your code could be simplified to -
$query = mysqli_query("SELECT a.year, a.emp_id, a.job_code, b.year prev_year, b.job_code prev_job_code FROM big_table a JOIN big_table b ON a.emp_id = b.emp_id AND b.year = a.year-1 WHERE a.job_code != b.job_code ");
$rows = array();
while ($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows);
note - you had mysqli_query(), but mysql_fetch_assoc(), so I updated to mysqli_fetch_assoc()
If you still wanted to do this in php, you need to save the last row value to a temporary array, and then check if the job_code has changed.
it would look something like this -
$query = mysqli_query("SELECT year, emp_id, job_code from big_table ORDER BY emp_id, year");
$temp = array();
$rows = array();
while ($r = mysqli_fetch_assoc($query)) {
if(!isset($temp[$r['emp_id']]){
$temp[$r['emp_id']] = $r; // add this row to the temp array
}
else {
if ($r['job_code'] != $temp[$r['emp_id']]['job_code']) {
// add the previous values for comparison
$r['prev_year'] = $temp[$r['emp_id']]['year'];
$r['prev_job_code'] = $temp[$r['emp_id']]['job_code'];
// add this row
$rows[] = $r; // add this row
// replace the last temp array with this array
$temp[$r['emp_id']] = $r;
}
}
echo json_encode($rows);
note - I changed the query by adding an ORDER BY -> ORDER BY emp_id, year

Why my script work half?

I’m using this code:
$date = date('Y-m-d');
$selStat = "SELECT obqva_id, COUNT(*) as broqch FROM statist WHERE date='$date' GROUP BY obqva_id ORDER BY COUNT(*) DESC LIMIT 8 ";
$queryStat = mysqli_query($conn, $selStat);
while ($rowStat = mysqli_fetch_array($queryStat)) {
$count = $rowStat['broqch'];
$id = $rowStat['obqva_id'];
echo $id.' - '.$count.'<br>';
$selBest = "SELECT * FROM view WHERE id='$id' GROUP BY $count ";
$queryBest = mysqli_query($conn, $selBest);
**$rowView = mysqli_fetch_array($queryBest);** this problem !
$selImage = "SELECT * FROM upload WHERE obqva_id='$id'";
$queryImage = mysqli_query($conn, $selImage);
$rowImage = mysqli_fetch_array($queryImage);
?>
Which produces this output:
First and next result has a problem, three and next have no problem... why?
First number 41 is ID next number total view.
it seems that the query is not valid, or there was no result.
thats why you get a bool instead of a resource.
you can filter that by putting your mysqli_query function in an IF statement, like this:
$selBest = "SELECT * FROM view WHERE id='$id' GROUP BY $count ";
if($queryBest = mysqli_query($conn, $selBest)){
$rowView = mysqli_fetch_array($queryBest);
}
else{
$rowView = false;
}
That's that, now for the query. You are trying to group the result on a number:
SELECT * FROM view WHERE id='$id' GROUP BY $count
Not sure why you want to group, as it seems that you only want to get some info on a specific id. In that case, i would get rid of the GROUP BY statement.

Sum up all the qty from a column

I have column qty in my table, and I want to sum up all the qty from this column in a variable:
$get_sold = "select qty from pending_orders where product_id='$p_id' AND order_status=='done'";
$result = mysqli_query($con, $get_sold);
try this.
$get_sold = "select sum(`qty`) as sum from pending_orders where product_id='$p_id' AND order_status='done'";
$result = mysqli_query($con,$get_sold);
$row=mysqli_fetch_assoc($result);
echo $row['sum'];
First you need sum to your column in your query by using sum(qty)as totals and also remove == from order_status it is =
you need to use mysqli_fetch_row to get your sum data into your variable
<?php
$get_sold = "select sum(`qty`)as totals from `pending_orders` where `product_id`='".$p_id."' AND `order_status`='done'";
$result = mysqli_query($con,$get_sold);
$row=mysqli_fetch_row($result);
$row[0];// get your total sum
try using, MySql sum function
$get_sold = "select sum(qty) total_qty from pending_orders where product_id='$p_id' AND order_status='done'";
$result = mysqli_query($con,$get_sold);
you should use
select sum(qty) as sumqty from pending_orders where product_id='$p_id' AND order_status='done'
Also mention, that in mysql you need to write on equal sign instead of two
Most people have responded here with a quick copy/paste, but I feel like it would be better suited to format your query nicely for readability sake to help you identify the issue.
$get_sold = "
SELECT SUM(`qty`) as `total_quantity`
FROM `pending_orders`
WHERE `product_id` = '$p_id' AND `order_status` = 'done'
";
$result = $con->query($get_sold);
if ( !$result ) {
die("MySQL error: " . $con->error);
}
$row = $result->fetch_assoc();
$quantity = $row['total_quantity'];
CHANE QUERY , SUM(column_name) gives sum of all numbers in column_name
$get_sold = "select SUM(qty) as total from pending_orders where product_id='$p_id' AND order_status='done'";

MYSQLI_QUERY not returning values

I am trying to figure out why my query is not working. I am trying to add all the amounts together for each month where status = 'S'. However, I get the following error. Any ideas?
[05-Jul-2013 11:21:30 America/New_York] PHP Fatal error: Cannot use object of type mysqli_result as array
My Code:
$closedsales = mysqli_query($mysqli, "SELECT MONTH(date) as month, sum(amount) as total FROM sales WHERE user_id = '".$userid."' AND status = 'S' GROUP BY MONTH(date)");
while ( $row = mysqli_fetch_row($closedsales) ) {
$closedsales[$row['month']] = $row['total'];
}
UPDATE:
$closedsales = mysqli_query($mysqli, "SELECT MONTH(date) as month, sum(amount) as total FROM sales WHERE user_id = '".$userid."' AND status = 'S' GROUP BY MONTH(date)");
while ( $row = mysqli_fetch_row($closedsales) ) {
$monthlysales[$row['month']] = $row['total'];
}
foreach($monthlysales as $monthlysale) {
echo $monthlysale;
echo "This worked...";
}
Thanks! I got rid of that error. However, for some reason my array does not contain anything. It only prints out This worked...
Is it possible this is because I don't have each month in the DB?
The problem is the assignment:
$closedsales[$row['month']] = $row['total'];
$closedsales is the result returned by mysqli_query, it's not an array you can assign to. Use a different variable for this.

Categories