Count column of table group by rows - php

I can count number of a table rows by using mysqli_num_rows. I have a table which contains similar rows. How can I count by grouping by similar row?
For instance: I have a table with 2 columns : Student and Option. Let say there are 50 students. 20 are in Economy option, 20 are in Management option and 10 are in Secretary Option. How can display those numbers. I can display only the 50.
my codes
$qry = "select * from table group by option";
$req= #mysqli_query($conn, $qry);
$result = mysqli_query( $conn, "select id from table");
$num_rows = mysqli_num_rows($result);
Students Total (<?php echo $num_rows ?>)
<table >
<tr>
<th>Student</th>
<th>Option</th>
</tr>
<?php
while($row=mysqli_fetch_array($req))
{
?>
<tr>
<td><?php echo $row['student'] ?></td>
<td><?php echo $row['option'] ?></td>
</tr>
<?php
}
?>
</table>

Here is the query you need:
SELECT COUNT(*) AS `option_count`, * -- returns a count aliased as "options_count"
FROM `table`
GROUP BY `option` -- will group the options and show the counts
Now you can echo the count, along with other data:
echo $row['count_options'];
echo $['options'];
The problem that you have here is that you will not be able to display each student in the option because this counts / groups only the three options.

Behold the proper query :
$qry = "select option as opt, COUNT(*) AS option from table group by option";

Related

MAX and COUNT sql query

I need to know how to use MAX() and COUNT() query to display the "fiser" table entries that contain the primary "codp" key that comes from the "products" table, depending on a previously selected period?
Table products : codp, denp ;
Table orders: codc,codp ;
Table returns : codr, datar, codc, codp
<?php
if(isset($_POST['add'])){
$sql = "SELECT p.denp, a.datar,MAX(p.codp)
FROM ( SELECT COUNT(p.codp) FROM products p ) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d') ";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
echo "
<table border=1 >
<tr>
<td><p> ".$row['codp']." </p></td>
<td><p> ".$row['denp']." </p></td>
<td><p> " .$row['codr']." </p></td>
<td><p> " .$row['datar']." </p></td>
<td><p> " .$row['codc']." </p></td>
</tr> </table> ";
}
} else {
echo " No results!" ;
}
}
?>
You should use group by for codp and the join the related result eg:
$sql = "SELECT p.denp, r.datar,MAX(p.cnt_codp)
FROM (
SELECT codp, COUNT(*) as cnt_codp FROM products
group by codp
) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d')
GROUP BY p.denp, r.datar ";
and you should check for your db driver for param bindig instead of use of php var in sql (you are at risk for sql injection)
and you should also use a group by for not aggreated column or reeval the question if you need the values related to max result (the use of aggregation function without a proper group by columns for not aggreagated is depreacted in sql ai the most recent version of mysql is not allowed)

How can I limit the display to distinct records?

As shown in the picture below, there are redundant records. How can the redundancy be removed?
Here's my code:
<?php
$YearNow=Date('Y');
include('../connection/connect.php');
$result = $db->prepare("SELECT * FROM studentvotes,student where student.idno = studentvotes.idno");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record" style="text-align:center;">
<td><?php echo $row['idno']; ?></td>
<td><?php echo $row['candid']; ?></td>
</tr>
<?php
}
?>
You need to use GROUP BY.
Change your SQL To:
SELECT * FROM studentvotes,student where student.idno = studentvotes.idno
GROUP BY student.idno
With GROUP BY, you specify a column (even multiple columns) to group with.
The results are grouped by those columns it means those columns (combinations if multiple) will come only once in the result set.
For example, your table has multiple entries of iDno.
When we fire SELECT query, it will return all rows having multiple instances of iDno.
If we apply GROUP BY, it will return results grouped by iDno.
just add groupby to your query like
$result = $db->prepare("SELECT * FROM
studentvotes,student
where student.idno = studentvotes.idno
GROUP BY student.idno
");
for more details please read #pupil Answer.
i hope this is working for you.
You can use GROUP BY for not displaying redundant records.
$result = $db->prepare("SELECT *
FROM studentvotes,
student
WHERE student.idno = studentvotes.idno
GROUP BY student.idno
");

Using php to compare mysql results, then echo differences?

I'm new to PHP and I'm trying to figure out how I can compare two mysql query results and echo out the differences. Basically I have a database that is comparing state flag characteristics. The user would select 2 states and what I would like is to have the php echo out 3 sets of results (state 1 only, shared characterisics, and state 2 only). My rough code below only echos out characteristics for states 1 and 2. Is there a way that I can compare the query results, so that I get differences between the states, and also shared characteristics.
<?php $query1 = $_GET['query1'];
$query2 = $_GET['query2'];
$min_length = 2;?>
<!-- state 1 characteristics only -->
<div class="fluid s1charc">
<?php echo "<strong><p>Search results for $query1</strong></p>";?>
<?php if(strlen($query1) >= $min_length){$query1 = htmlspecialchars($query1);
$query1 = mysql_real_escape_string($query1);
$raw_results1 = mysql_query("SELECT * FROM charc_s WHERE `charc_f` ='$query1' ORDER BY FLAG_S") or die(mysql_error());
if(mysql_num_rows($raw_results1) > 0) {
while($results1 = mysql_fetch_array($raw_results1)){
echo "<table id='iseqchart' class='sortable'>
<tr valign='middle'>
<td ><a href='flag.php?FLAG_ID=".$results1['FLAG_ID']."'><img src='images/".$results1['IMAGE']."'></a></td>
<td> </td>
<td><strong><font size='3'><a href='flag.php?FLAG_ID=".$results1['FLAG_ID']."' style='color:#100783'>".$results1['FLAG_S']." (".$results1['STATE'].")</strong></a>
</td>
</tr>
</table>";
}
}
else{ // if there is no matching rows do following
echo "No results were found";
}
}
else{ // if query length is less than minimum
echo " ".$min_length;
}
?>
</div>
<!-- shared characteristics -->
<div class="fluid sharecharc">Shared</div>
<!-- state 2 characteristics only -->
<div class="fluid s2charc">
<?php echo "<strong><p>Search results for $query2</strong></p>"; ?>
<?php if(strlen($query2) >= $min_length){$query2 = htmlspecialchars($query2);
$query2 = mysql_real_escape_string($query2);
$raw_results = mysql_query("SELECT * FROM charc_s WHERE `charc_f` ='$query2' ORDER BY FLAG_S") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0) {
while($results = mysql_fetch_array($raw_results)){
echo "<table id='iseqchart' class='sortable'>
<tr valign='middle'>
<td ><a href='flag.php?FLAG_ID=".$results['FLAG_ID']."'><img src='images/".$results['IMAGE']."'></a></td>
<td> </td>
<td><strong><font size='3'><a href='flag.php?FLAG_ID=".$results['FLAG_ID']."' style='color:#100783'>".$results['FLAG_S']." (".$results['STATE'].")</strong></a>
</td>
</tr>
</table>";
}
}
else{ // if there is no matching rows do following
echo "No results were found";
}
}
else{ // if query length is less than minimum
echo " ".$min_length;
}
?>
</div>
The best way to do this is on the server side. Make the database do 3 different selects. The reason is that the server will run the queries a lot faster than the php. And it will end up in a better user experience.
Only Table A
SELECT * FROM TableA A LEFT JOIN TableB B ON A.key = B.key
Only Table B
SELECT * FROM TableA A RIGHT JOIN TableB B ON A.key = B.key
And in Both Tables
SELECT * FROM TableA A INNER JOIN TableB B ON A.key = B.key
From there echo out your results.

Combining multiple MySQL queries into 1

I am trying to display a summary table which is currently using multiple MySQL queries and I was wondering if it's possible to combine them into one.
I have a table called 'payments' with the fields amount and currency, and i'm trying to display a summary totals table for each of the currencies. As an example:
<table>
<tr>
<td>USD</td>
<td>EUR</td>
<td>GBP</td>
</tr>
<tr>
<? $q1 = mysqli_query("SELECT sum(amount) as total_USD from payments WHERE currency='USD'");
while($row1 = mysqli_fetch_assoc($q1)){ ?>
<td><? echo number_format($row1['total_USD'],0); ?></td>
<? } ?>
<? $q2 = mysqli_query("SELECT sum(amount) as total_EUR from payments WHERE currency='EUR'");
while($row2 = mysqli_fetch_assoc($q2)){ ?>
<td><? echo number_format($row2['total_EUR'],0); ?></td>
<? } ?>
<? $q3 = mysqli_query("SELECT sum(amount) as total_GBP from payments WHERE currency='GBP'");
while($row3 = mysqli_fetch_assoc($q3)){ ?>
<td><? echo number_format($row3['total_GBP'],0); ?></td>
<? } ?>
</tr>
</table>
In reality, I am using 12 currencies so I have 12 separate queries but it feels inefficient so I was wondering if there is an easier way to achieve the same result?
Many thanks!
SELECT currency,
SUM(amount) as total
FROM payments
GROUP BY currency
Solution 1:
SELECT currency, SUM(amount) as total FROM payments GROUP BY currency
Solution 2 :
$currencies=array(USD,EUR,GBP,...);
foreach($currencies as $currency){
$q1= mysqli_query("SELECT sum(amount) as total from payments WHERE currency='".$currency."'");
while($row1 = mysqli_fetch_assoc($q1)){
echo number_format($row1['total'],0);
}
}
You can use a GROUP BY here.
SELECT currency, SUM(amount) as total FROM payments GROUP BY currency
http://dev.mysql.com/doc/refman/5.1/en/group-by-modifiers.html

Combine total count for entries in 2 SQL tables

I can't seem to find the right way to do this so I was hoping someone could give me some direction?
The SQL Database is structured like this (I've removed the irrelevant stuff):
Requests
R_ID R_FulfilledBy
1 Bob
2 Craig
3 Bob
SIMs
SM_ID SM_FulfilledBy
1 Bob
2 Craig
3 Bob
I'm hoping to end up with this output:
Fulfilled By Requests
Bob 4
Craig 2
Here's my PHP/HTML:
<div id="table">
<?php
//Connect to MySQL Database
$connection = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass);
mysql_select_db($runnerdbName, $connection) or die("MysQL Error");
$query = "SELECT R_FulfilledBy, COUNT(R_ID) FROM Requests GROUP BY R_FulfilledBy ORDER BY COUNT(R_ID) DESC";
$result = mysql_query($query) or die(mysql_error());
?>
<!-- Number of Runners (Counts total number of records in Requests table) -->
<table border='0' width='50%'>
<tr>
<th>Runners Fulfilled</th>
<tr><td><?php
$query = mysql_query("SELECT * FROM Requests");
$number=mysql_num_rows($query);
echo $number;
?>
</td></tr>
</table>
<!-- Fulfillment Stats -->
<table border='0' width='50%'>
<tr>
<th>Name</th>
<th>Runners Fulfilled</th>
</tr>
<?
// Print out result (I want this to calculate requests fulfilled by each user in 'Requests' and 'SIMs' table)
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['R_FulfilledBy'] ."</td>";
echo "<td>". $row['COUNT(R_ID)'] ."</td>";
echo "</tr>";
}
?>
</table>
At present it's only calculating the records from the 'Requests' table :(
You could union all the two tables together in a subquery:
select FulfilledBy
, count(*)
from (
select R_FulfilledBy as FulfilledBy
from Requests
union all
select SM_FulfilledBy
from SIMs
) as SubQueryAlias
group by
FulfilledBy
Use union all instead of union because the second eliminates duplicates; which would give everyone a maximum count of 1.
I'd go with this:
SELECT R_FulfilledBy, COUNT(*) +
( SELECT COUNT(*) FROM SIMs WHERE R_FulfilledBy = SM_FulfilledBy )
FROM Requests GROUP BY R_FulfilledBy

Categories