how to display value of mysql sum query - php

I am trying to grab the total amount of sales made for a a single month
$aug11 = mysql_query("SELECT SUM(price) FROM table WHERE sales_date LIKE '08/%/2011' ");
when I echo $aug11 I get a resource id# error. I also tried to do this
$test1 = mysql_fetch_array($aug11);
and when I echo $test1 it just says "Array".
Is it absolutely necessary to place a GROUP by sales_date in the original query and then have a while loop that grabs the array and lets me echo the values?
I don't really need any other value except the sum of 'price' for the month of August.
Can someone please explain to me how I can display the value I need without a while loop?

use this to get the sum value
$test1[0];

echo $test1[0]; // returns the sum

$aug11 is not a query string, it is the result of a query. When you fetch an array from the result, it is an array of values, not a scalar. I think you want to do this:
$query = "SELECT SUM(price) FROM table WHERE sales_date LIKE '08/%/2011'";
$aug11 = mysql_query($query);
$row = mysql_fetch_array($aug11);
$test1 = $aug11[0];

Related

How to get the count of a specif value from a single column

I was working with a project where I want to get the count of values in a column. I will explain with an example.
I have a table column named name. Where it's values are A,B,C,D,A,D,B,A,C.
Now I want the output as
Count: A-3,B-2,C-2,D-2.
I have tried using group by and distinct. but both don't give me what I want. It all getting the total count of that item. In the code given below is the query I tried. There I want the count of particulars_id and the $public_page_id will be common for all particulars_id I am fetching. There will be a number of public_page_id in the table, and each will have some particulars_id under them.
$output = '';
$this->db->select('COUNT(service_appointment_details.particulars_id)
as count,particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_id');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db-
>join('service_appointment_details','particulars.public_page_id =
service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();
Expected Result
Expected Result is (based on the above example)
Count: A-3,B-2,C-2,D-2.
Actual Result
But what I'm getting now is
Count: A-9,B-9,C-9,D-9.
I need to fetch count of each particulars_id under the given public_page_id
You should use count(*)
$this->db->select('COUNT(*) as count,particulars.particulars_name');
........
As pointed out by #scaisEdge, you need to use count(*) instead of count(service_appointment_details.particulars_id). By using count(service_appointment_details.particulars_id), you basically count the number of rows from your select which is not what you want.
Final snippet would be:
$output = '';
$this->db->select('COUNT(*) as count, particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_name');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db->join('service_appointment_details','particulars.public_page_id = service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();
Whenever you want to count occurrence of a column values, you'd do
SELECT column_to_count, count(*) FROM table GROUP BY column_to_count

Using Count giving wrong number of rows

Before I was using this code to count rows
echo $db_handle->numRows("SELECT * FROM orders WHERE DATE(reattemptdate) = CURDATE()");
than i found it effects on performance, than i tried to use below code, but it not giving correct number of rows, what wrong i done in below code ?
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
$numrowsresultdelivery =count($resultdeliverys);
echo $numrowsresultdelivery;
Database connection code :
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
In your second code, the query will always return 1 row - a row with the column count being the number of rows, so...
$numrowsresultdelivery =count($resultdeliverys);
Will probably always be 1, you need something like...
$numrowsresultdelivery =$resultdeliverys[0]['count'];
to extract the count field from the first row of the result.
(Note I don't know if this is the right notation, but it's the principle of needing a field from the result rather than the number of results.)
You must already have the count number via $resultdeliverys->count.
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
// Try this to know if it's returning array or object
var_dump($resultdeliverys);

Php code that will output the value(can be number or literals) of sql

I have this:
$query = "SELECT time FROM table_schedule GROUP BY time ORDER BY count(*) desc LIMIT 1 ";
then I stored it in:
$result = mysql_query($query);
I will output the value by <?php echo $result ?> but I am always getting this value Resource id #20.
I am new in sql so I hope someone can help me with my problem.
You are trying to show the result in a unproper way. In PHP mysql_query() will execute a query. In order to get the result, you should use
$result = mysql_query($query);
$row=mysql_fetch_array($result); // fetches the result of the query and stores in an associative array
$time=$row['time']; // get the result from the associate array with field name as the index
You can also use ,
$row=mysql_fetch_row($result);
$time=$row[1];
which will fetch the result as an enumerated array where you want to display each fields with the column number starting from 0.
For reference

MySQL COUNT query results in 1 always

I'm wondering why my MySQL COUNT(*) query always results in ->num_rows to be equal 1.
$result = $db->query("SELECT COUNT( * ) FROM u11_users");
print $result->num_rows; // prints 1
Whereas fetching "real data" from the database works fine.
$result = $db->query("SELECT * FROM u11_users");
print $result->num_rows; // prints the correct number of elements in the table
What could be the reason for this?
Because Count(*) returns just one line with the number of rows.
Example:
Using Count(*) the result's something like the following.
array('COUNT(*)' => 20);
echo $result['COUNT(*)']; // 20
Reference
It should return one row*. To get the count you need to:
$result = $db->query("SELECT COUNT(*) AS C FROM u11_users");
$row = $result->fetch_assoc();
print $row["C"];
* since you are using an aggregate function and not using GROUP BY
that's why COUNT exists, it always returns one row with number of selected rows
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Count() is an aggregate function which means it returns just one row that contains the actual answer. You'd see the same type of thing if you used a function like max(id); if the maximum value in a column was 142, then you wouldn't expect to see 142 records but rather a single record with the value 142. Likewise, if the number of rows is 400 and you ask for the count(*), you will not get 400 rows but rather a single row with the answer: 400.
So, to get the count, you'd run your first query, and just access the value in the first (and only) row.
By the way, you should go with this count(*) approach rather than querying for all the data and taking $result->num_rows; because querying for all rows will take far longer since you're pulling back a bunch of data you do not need.

Adding up values inside of a while loop

With the first query in the following code I am looking for the checkings made in Berlin under the game number two.
With the second query I want to give points for each of the checkings.
As you will see I am using the function SUM. But let's say that I have 2 checkings and the points for each checking are 50. Well, instead of echoing 100, with this code I echo 5050
What is wrong with it?
Thanks a lot
THE CODE IS CORRECTED AND WORKING, JUST IN CASE SOMEBODY NEEDS IT. Thanks to all
$querya = "SELECT * FROM checkins where gamesid=2 and city='Berlin'";
$resulta = mysql_query($querya) or die(mysql_error());
$sumOfPoints = 0;
while($rowa = mysql_fetch_array($resulta)){
$n = $rowa['venuesid'];
$queryb = "SELECT venuesid, SUM(points) as sumpoints from venues where venuesid='".$n."' GROUP BY venuesid ORDER BY venuesid";
$resultb = mysql_query($queryb) or die(mysql_error());
while($rowb = mysql_fetch_array($resultb)){
$sumOfPoints += $rowb['sumpoints'];
}
}
echo "Total points is $sumOfPoints<br/>";
Some suggestions
Use SUM(points) AS sum (only for clarity when use the sum)
Check that points are numerical fields not varchar.
points must be a string, you need to cast it
SUM(cast(points) as int)
and then follow Gaurav's point about labeling the compute
You're getting 5050 because your script is echoing 50 in two iterations of the loop.
From the looks of it, your second query's GROUP BY clause is not grouping on venuesid when it should be. So, first try changing your GROUP BY clause to:
GROUP BY venuesid
If that doesn't give you the result you're looking for, then you should try running your query directly against the database with a static value for venuesid to see what you get back from it, then perhaps update your question and we can take it from there.

Categories