MySQL Count number of Items with Group By - php

We have these two fields in our MySQL database:
in_model , in_color
And we are trying to count the total of model (in_model field), which has the same color (in_color field) in PHP with MySQL as backend database. We tried using the count() function, together with the group by. But it would seem we don't have achieve a desired result
This is our MySQL database:
$query = "SELECT in_model, COUNT(in_color) FROM in_newunit GROUP BY in_color,in_model";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)) {
echo "There are ". $row['COUNT(in_color)'] ."
". $row['in_model'] ." items.";
echo "<br />";
}
This is the output we are receiving
There are 1 C2I items.
There are 2 try items.
There are 2 try items.
There are 4 C2I items.
This is what we are trying to achieve
We are trying to have the color appear in the echo
There are 1 C2I Black items.
There are 2 try White items.
There are 2 try Black items.
There are 4 C2I White items.

I think this is straight enough. Try this.
$query = "SELECT in_model, in_color, count(*) AS counter FROM in_newunit GROUP BY in_model, in_color";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)) {
echo "There are ". $row['counter'] ." ". $row['in_model'] ." ".$row['in_color']." items.";
echo "<br />";
}

The query is actually the other way around:
SELECT in_color, count(*) FROM in_newunit
GROUP BY in_color
And you have actually said it yourself:
we are trying to count the total of model (in_model field), which has the same color (in_color field)
"count the total of model" > count(*)
"which has the same color" > for every color the previous count, which is a group by in_color
Also note that if you do count(in_model) you won't be counting values with in_model as null. If you do count(*) you will be counting the null values too. Up to you.
Update
So you want the amount of elements there are by (model, color) pair. Then this is the query:
SELECT in_model, in_color, count(*) FROM in_newunit
GROUP BY in_model, in_color
Eg:
model1 | black | 2
model1 | white | 1
model2 | black | 5
model3 | white | 4

Related

PHP MYSQL, two tables

I have two tables and i want to echo the total call count once each user logins:
Login
Firstname | Lastname | Login ID
------------------------------
Tyler | Durden | 3
Call Count
Name | Call Count | Open | GrandTotal
------------------------------
Tyler Durden| 100 | 33 | 133
i tried:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name=".$_SESSION['firstname']. ' ' .$_SESSION['lastname']." ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
But its not working, i think i have to join the the two tables to get it to work. What do you think?
Assuming your Call Count table is actually called csvdata, you'll want to format your SQL request string a bit by adding single quotes around the WHERE name = part.
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name='".$_SESSION['firstname']. ' ' .$_SESSION['lastname']."' ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Call Count'].' Call Count';
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
Good practice would require that you use primary keys to facilitate joins between tables and make sure two users with the same name can be differenciated.
In that case you may want to consider replacing the Name column in your Call Count table for your loginID. This way you could get your name from the Login table (as shown below). Also, as bad as it is to have duplicated data like your user's name in both tables, you do not need your GrandTotal column since you can easily get the sum of CallCount and Open to get the exact same number. In the end, your query should look more like this (assuming your tables are called Login and CallCount).
<?php
$result = mysqli_query($mysqli, "SELECT l.FirstName, l.LastName, cc.CallCount, cc.Open, (cc.CallCount + cc.Open) AS GrandTotal FROM Login AS l JOIN CallCount AS cc ON l.LoginID = cc.LoginID WHERE l.FirstName LIKE \"".$_SESSION['firstname']."\" AND l.LastName LIKE \"".$_SESSION['lastname']."\"");
// ...
?>

Find MIN -values but maintain row values in PHP mysqli

I have a table with 32 rows, with pairwise rows containing same "name-values", but with different raspberry-values (respectively "one" and "two".)
I want to extract each row with a unique name and the lowest average_distance - giving me 16 rows, and for that I am using this query:
SelectFinally();
function SelectFinally (){
$con = connectToDB();
$sql = "SELECT name,MIN(average_distance),raspberry From average GROUP BY name";
$result= mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
echo "number of rows" .$num_rows ."<br />";
while($row=mysqli_fetch_assoc($result)) {
extract($row);
$name = $row['name'];
$distance = $row['MIN(average_distance)']; //."<br />";
$raspberry = $row['raspberry']; //."<br />";
echo "select inside selectFinally name: " .$name ." distance: " .$distance ." raspberry " .$raspberry ."<br />";
}
}
This query gives me the lowest values of the average_distance allright, BUT it messes up my raspberry values. e.g. blÄ_bil should have a raspberry value of "two", hence it has the lowest average_distance - value.
I can not seem to get it right. Would somebody please help me to get it right?
try:
SELECT a.name, a.raspberry
FROM average a
INNER JOIN
(
SELECT name, MIN(average_distance) as avg_dist
FROM average
GROUP BY name
) a2 ON a.name = a2.name AND a.average_distance = a2.avg_dist
Instead of SELECT name,MIN(average_distance),raspberry From average GROUP BY name
thanks Nishant Matha
It worked - I simply needed to add te raspberry in my first select. Now it adds the average_distance to the output.
$sql = "SELECT a.name, a.average_distance, a.raspberry
from average a
INNER JOIN
(
select name,MIN(average_distance) AS avg_dist,raspberry
FROM average
GROUP BY name
)
a2 ON a.name=a2.name AND a.average_distance = a2.avg_dist ";

php database table select limited

im new on php programming and i've searched the function that i need but didn't found it.
here what exactly i want to do :
i want to select 2 columns from a table
set the order by descending by 1 column that is numeric
and then show in php the first 100 rows that were selected
Here is my code right now php shows all the columns i want it to show the first 100
$result = mysqli_query($con,"SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC");
while($row = mysqli_fetch_array($result))
{
echo $row['pvpkills'] . "&nbsp " . $row['char_name'];
echo "<br>";
}
SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC LIMIT 0,100

Find Duplicate Rows/Records from Table

Here is my table structure,
Im try run query
$sql = mysql_query("SELECT content,niche, COUNT(content) TotalCount FROM table_name GROUP by content HAVING COUNT(content)>=2");
I i think is give me corect result, but have problem to list result with php and make delete button to delete one of duplicated rows
Im get result in php
Content ID - Niche ID - TotalCount
208 - 2 - 2
210 - 32 - 3
But result should be
Content ID - Niche ID - TotalCount
208 - 2 - 2
208 - 2 - 2
210 - 32 - 3
210 - 32 - 3
210 - 32 - 3
im try result display with php
while($row = mysql_fetch_assoc($sql)) {
$array[] = $row;
}
foreach($array as $row) {
echo $row['content']." - ".$row['niche']." - ".$row['TotalCount']."<br>";
}
GROUP BY will collapse the results on the field you're grouping, in this case content - hence why you only see two results.
If you want to keep the GROUP BY technique, you can also use GROUP_CONCAT(niche) to pull a comma-separated list of each niche for a given content value:
SELECT
content,
GROUP_CONCAT(niche) AS niche,
COUNT(content) TotalCount
FROM
table_name
GROUP BY
content
HAVING
COUNT(content)>=2;
You can then use PHP's explode(',', $row['niche']) to get each distinct value and then use those to determine which one you want to delete.
foreach($array as $row) {
$niches = explode(',', $row['niche']);
foreach ($niches as $niche) {
echo $row['content'] . " - " . $niche . " - " . $row['TotalCount'] . "<br />";
}
}
I think this is what you're asking for, all duplicate rows (with row_id) and how many times they are duplicated;
SELECT a.row_id, a.content, a.niche, cnt
FROM table_name a
JOIN (
SELECT MIN(row_id) m, COUNT(*) cnt, niche,content
FROM table_name
GROUP BY content,niche
HAVING COUNT(*)>1
) b
ON a.niche=b.niche
AND a.content=b.content
An SQLfiddle to test with.
Make the following change in sql:
$sql = mysql_query("SELECT content,niche, COUNT(content) TotalCount FROM table_name HAVING COUNT(content)>=2");

Join two MySQL Tables and display combined data

I have two tables in my database.
cat - catid, catname
articles - id, catid, content
so what i want to display is category name (catname) and how many articles are there in that category.
This is my code but it dosent work.
$query = "SELECT cat.cname, COUNT(articles.cat_id)".
"FROM cat, articles ".
"GROUP BY cat_id";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['cname']. " - ". $row['COUNT(cat_id)'];
echo "<br />";
}
Any help will be most aprriceated. thanks.
So this is a 1:many relationship. i.e. 1 Category -> Many articles.
The best way to do this is to create a third table, an adjacency list.
Keep your 'category_id' and 'article_id' unique in tables 'cat' and 'article'.
In your third table you define the 1 : many relationships.
Table 3: cat_articles
adj_id cat_id art_id
1 1 1
2 1 2
3 2 3
4 2 4
5 3 5
Now join the tables:
$sql = "SELECT * FROM `cat_articles` adj ".
"LEFT JOIN (`cat` cat, `articles` art)".
"ON (cat.cat_id = adj.cat_id AND art.art_id = adj.art_id) ";
This takes the adjacency table, preserves it's format(due to left join) and appends the tables article and category to it, giving you a categorised table of all your articles. You can now use mysql_fetch_array() to get your results.
Edit: reference first comment, displaying number of rows
You can either, as you have done, use SQL's function COUNT to return a count of a specific column.
Or, with PHP, run the query, and then use mysql_num_rows($result) to return the number of rows SQL has in its buffer.
Alternatively, retrieve results using mysql_fetch_array($result) and use count to return the number of paired values in the array.
Using mysql_fetch_array:
$query = "SELECT cat.cname, COUNT(articles.cat_id)".
"FROM cat, articles ".
"GROUP BY cat_id";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row[0]. " - ". $row[1];
echo "<br />";
}
mysql_fetch_array returns a number indexed array (0,1,2,3,4, ..)
SELECT cat.cname, COUNT(articles.cat_id) artcount
FROM cat, articles WHERE c.cat_id = articles.cat_id
GROUP BY cat.cat_id
I guess you are missing the join clause. Unless you are joining the tables correctly you are creating a "cartesian product".
Get the rows "$row['cname'] and $row['artcount'].

Categories