简体   繁体   中英

Populate HTML table from MYSQL and counting rows

I'm trying to populate a HTML table with mysql data, I have the following data in Mysql:

ID, IP, Referal

I want to create a table that shows a list of the referals and how often they occur, for example:

ID,    IP,      Referal
1     1.1.1.1   google.com
2     2.2.2.2   google.com
3     3.3.3.3   test.com
4     4.4.4.4   another.com

Should output:

google.com     2
test.com       1
another.com    1

What I've tried was this:

<table class="table table-bordered table-primary">
<tbody>
<?php
$sql="SELECT * FROM traffic";
$result=mysql_query($sql);
?>
<?php while($row = mysql_fetch_array($result)) { ?>
<tr >
<td class="tc"><font face="Arial, Helvetica, sans-serif"><?php if($row['referal']==''){
echo "Empty Referal";
} else { echo $row['referal']; }?></font></td>

<td class="tc"><center><font face="Arial, Helvetica, sans-serif"><?php $referal = $row['referal'];
$sql="SELECT COUNT(*) FROM traffic WHERE referal = $referal";
$num_rows = mysql_num_rows($result);

echo "$num_rows";

?></font></center></td>

</tr>
                    <?php } ?>
            </tbody>
        </table>

But that didn't count each refer individually, also it created a new table row for each entry even if the referal was the same.

Any help is greatly appreciated.

The thing is that you are gathering the amount of rows found in your last query and NOT your count query:

$sql="SELECT COUNT(*) FROM traffic WHERE referal = '$referal'";
$num_rows = mysql_num_rows($result);

First off, the COUNT command will return you a single row with a single column containing the count found. You should use the following:

$sql="SELECT COUNT(*) as count FROM traffic WHERE referal = '$referal'";
$numResult = mysql_fetch_array(mysql_query($sql));
$num_rows = $numResult['count'];

Also, it is VERY unneeded to put quotes around a variable you are echoing. This will suffice:

echo $num_rows; //NOT echo "$num_rows";

NOTICE: Do not use MySQL_* functions as they have been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead.

You are probably looking for the GROUP BY keyword of SQL:

SELECT Referal, COUNT(*) FROM traffic GROUP BY Referal

This will give you exactly the table you want, without any additional for-loop in php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM