php - mysqli count rows with specific value - php

At the moment I'm able to count all the record's in a table with the value "Waiting". This is done by using:
$query = "SELECT COUNT(*) AS SUM FROM jobs WHERE status='Waiting'";
When I want to echo the row count I just do:
echo $rows['SUM'];
How can I do it so it also count's all the record's in a table with the value "Ready"?

This query will return all status count divided by status:
SELECT status, COUNT(status) AS tot FROM jobs GROUP BY status
The resulting set is something like this:
status tot
----------- ------
Waiting 123
Ready 80
... 56

So you want status='Waiting' or status='Ready'? You can separate parameters with OR or AND; for example:
$query = "SELECT COUNT(*) AS SUM FROM jobs WHERE status='Waiting' OR status='Ready'";

SELECT count(status) AS 'count' FROM jobs GROUP BY status HAVING status='Ready'
This will count the records with the status = Ready. You use GROUP BY to get an aggregate on the status field. And because you have used GROUP BY, you use HAVING (which is the equivalent of WHERE in GROUP situations) to filter the data.

By using IN operator in your query.
$query = "SELECT COUNT(*) AS SUM FROM jobs WHERE status IN ('Waiting','Ready')";
Get group based(status) counts by using GROUP BY operator
$query = "SELECT COUNT(*) AS SUM FROM jobs GROUP BY status";
Print the status based result.
//Create the `mysqli_connection` and assign to `$conn` variable.
$result = mysqli_query($conn, $query);
if($result->num_rows>0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<br>status=" . $row['status'];
echo "<br>SUM=" . $row['SUM'];
}
}

Related

Unable to get the value from a query with WHERE Clause

I am trying to get the Total Sum of values from a table. Query works without WHERE Clause, but i need to get the total sum per user. Like user ABC has 100USD and user BDC has 200USD. Here is the code
$PWithdrawls = mysqli_query($con, "SELECT * FROM withdraw WHERE status='Pending'");
$S_NO = 0;
while ($row = mysqli_fetch_assoc($PWithdrawls)) {
$S_NO++;
$posted_by = mysqli_query($con,"SELECT * FROM users WHERE userId=".$row['seller_id']);
$user_ad = mysqli_fetch_assoc($posted_by);
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id']);
$sum_amount = mysqli_fetch_assoc($TotalOrders_Amount);
$sum = $sum_amount['total'];
And here is my call
<td>$<?php echo $sum; ?></td>
Here is DB
Think you have error in your SQL Query:
SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id'] GROUP BY userId LIMIT 1
You need to use GROUP BY to get actual SUM. Also you can get all users with Total, there is no need to second query:
SELECT u.*, SUM(o.amount) AS total
FROM users u
LEFT JOIN orders o ON (o.userId = u.id)
GROUP BY u.userId
This should get you entire user row + total of their orders.
I found the issue. I was calling the wrong variable. userId was not in my table, it was seller_id. So correct query was
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE seller_id=".$row['seller_id']);
Thanks to everyone. I really appreciate.

SUM of columns while grouping by other column

So this is the structure of my MySQL table that I wanna work this out with:
ID type category_id amount
12 Expense 3 963.39
13 Expense 5 1200.50
14 Expense 3 444.12
15 Expense 5 1137.56
..............................
Desired output:
1407,41 (for category_id = 3)
2338,06 (for category_id = 5)
....... (and for other category_id)
What I get now:
1407,41 (only for category_id = 3)
My query does not add or display the sum of other category_id.
This is the query I am trying:
$query = "SELECT SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
$expense_count = mysqli_fetch_array($expense_query);
echo $expense_count[0];
Been stuck with this for the last couple of days. Any help is very much appreciated. Thank you!
You're only calling mysqli_fetch_array() once. You need to call it in a loop to get all the totals. You should also include the category ID in the SELECT list.
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
echo "{$row['TotalAmount']} (for category_id = {$row['category_id']}<br>\n";
}
The query here works. It's just that you only select the first result from the $expense_count variable. $expense_count[1] will return the second category listed, $expense_count[2 will return the third one, ect...
Try echo implode(" <br>", $expense_count);
Have a nice day.

Select from 2 tables not working with php mysql

I have two different tables of the following structure:
grouprel
id | userId | pupID | groupId
pupils
id | userId | fname | lname
pupId in groulrel is equal to id in pupils.
I want to fetch pupils from a different group and then order them by fname, lname.
Now I have two queries like this:
$q = "SELECT * FROM grouprel WHERE userid = ". $userid ." AND groupId = ". $_GET['id'] ."";
$r = mysqli_query($mysqli, $q);
while ($rows = mysqli_fetch_object($r)) {
$query = "SELECT id, fname, lname FROM pupils WHERE userid = ". $userid ." AND id = ". $rows->pupId ." AND status = 0 ORDER BY fname, lname";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_object($result)) {
echo stuff...
}
}
This works, but it doesn't order the names alphabetically like I want to.
How could I fix this?
This is iterating over the first query:
while ($rows = mysqli_fetch_object($r)) {
And this iterates over each instance of the second query:
while($row = mysqli_fetch_object($result)) {
So if the first query returns 1,2,3, and each iteration of the second query returns A,B, then your output would be:
1 A
1 B
2 A
2 B
3 A
3 B
The second query is ordering by the ORDER BY clause you gave it. But you are ordering the entire output by the first query.
Ultimately, why do you need these separate queries at all? Executing a database query in a loop is almost always the wrong idea. It looks like all you need is one query with a simple JOIN. Guessing on your logic, something like this:
SELECT
pupils.id, pupils.fname, pupils.lname
FROM
pupils
INNER JOIN grouprel ON pupils.id = grouprel.pupId
WHERE
pupils.userid = ?
AND grouprel.groupId = ?
AND pupils.status = 0
ORDER BY
fname, lname
It may take a little tweaking to match exactly what you're looking for, but you can achieve your goal with a single query instead of multiple separate queries. Then the results of that query will be ordered the way you told MySQL to order them, instead of the way you told PHP to order them.

How to get the minimum id from the table in MySql

I have written a MySql query to get the columns related with minimum id . Looks something like this
SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed=21
The table has 4 rows looks like this
So according to the function that I have written
function setLC()
{
$sql = "
SELECT min(id) as ID
, feed
, idpropiedad
FROM `registrofeed`
WHERE feed=21
";
$result = $this->localDb->execute($sql);
$row=mysql_fetch_array($result);
echo $sql;
echo $row['idpropiedad'];
$this->lastCode = $row['idpropiedad'];
}
It returns empty string for idpropiedad
Can any one help me out where I am going wrong
Thanks in advance
I'd think the query you're actually looking for is this:
SELECT id, feed, idpropiedad
FROM registrofeed
WHERE feed = 21
ORDER BY id ASC
LIMIT 1
MIN() is giving you the generally lowest value in the column, it does not affect the rest of the columns. If you want the whole row with the lowest id it doesn't help.
To illustrate, if you really wanted to use MIN here, you'd have to do:
SELECT id, feed, idpropiedad
FROM registrofeed
WHERE id = (SELECT MIN(id) FROM registrofeed WHERE feed = 21)
You can do a better query like this:
$sql = "
SELECT id as ID
, feed
, idpropiedad
FROM `registrofeed`
WHERE feed=21
HAVING MIN(id)
";
This will return only one row with the minimum id number. It's more readable than using ORDERING AND LIMIT 1.
try your select query as
SELECT * FROM registrofeed WHERE feed='21' ORDER BY id ASC LIMIT 1
this fetches the row having minimum id.
Hope it helps
Try this
$sql = "SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed='21' order by id asc";

PHP, SQL - getting fetch where table id = user id and count other table where row is = user id

Thanks for helping, first I will show code:
$dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESSION['user_id']."' and contracts.customer_contract = ".$_SESSION['user_id']." order by COUNT(contracts.customer_contract) DESC limit $limit, $pocetZaznamu ";
I need to get the lists of users (customers table) ordered by count of contracts(contracts table)
I tried to solve this by searching over there, but I can't... if you help me please and explain how it works, thank you! :) $pocetZanamu is Number of records.
I need get users (name, surname etc...) from table customers, ordered by number of contracts in contracts table, where is contract_id, customer_contract (user id)..
This should do it where is the column name you are counting.
$id = $_SESSION['user_id'] ;
$dotaz = "Select COUNT(`customer_contract`) AS CNT, `customer_contract` FROM `contracts` WHERE `user_id`=$id GROUP BY `customer_contract` ORDER BY `CNT` DESC";
Depending on what you are doing you may want to store the results in an array, then process each element in the array separately.
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
$contracts[$row[1]] = $row[0];
}
foreach ($contracts AS $customer_contract => $count){
Process each user id code here
}
Not sure what you are counting. The above counts the customer_contract for a table with multiple records containing the same value in the customer_contract column.
If you just want the total number of records with the same user_id then you'd use:
$dotaz = "Select 1 FROM `contracts` WHERE `user_id`=$id";
$results = $mysqli->query($dotaz);
$count = mysql_num_rows($results);

Categories