Populate HTML table from MYSQL and counting rows - php

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.

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 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.

Related

php table <th> and <td> from Database Selected but they are not Matching in the right indexing position

all Developers.
I am developing School Management System, in the Database, I have two tables one is For Subjects, and the other one is designed for obtained marks of the Subjects and it is called scores.
So I am trying to fetch subject Names as Table Head
I have another Query below this query and I am trying to fetch from scores as table data .
At this point, I failed to match the subject name and its score from the scores table.
Here is my code:
<table class="table table-striped table-bordered">
<head>
<tr>
<?php
// Query for Subject Names
$view_subject = $config->prepare("SELECT * FROM subjects");
$view_subject->execute();
while($row = $view_subject->fetch()){
$sub_name = htmlspecialchars($row['sub_name']);
?>
<th class="text-center"style="background-color:#395C7F;color:#fff;"><?php echo $sub_name;?></th>
<?php } ?>
</tr>
</thead>
<body>
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]);
while($row = $view_scores->fetch()){
$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);
?>
<tr>
<td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
</tr>
<?php } ?>
</tbody>
</table>
Database images:
1- Subjects table
2- Scores table
** Browser UI **
On your second loop you have entered '<tr>' wrapping each '<td>' that means that each one arrives at a different line , '<td>'s should be as much as there are '<th>' for each line.... so :
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]);
?>
<tr>
<?php
while($row = $view_scores->fetch()){
$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);
?>
<td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
<?php } ?>
</tr>
</tbody>
</table>
This should fix your table but it will only create one line! if you have more than one line you will need to add another loop to wrap this one and it will create the new '<tr>' outside the inner loop.
BTW: I assume that the 2nd while loop is exactly long as the first one... since you are supposed to have the same amount of <td> per line per <th> if it's not in the same length or not sorted the same way you will have an issue... which can be resolved either by adjusting your SELECT or creating an array with ids and injecting to it the data from the second loop according to the keys brought in the first.

How do I add another mysqli query into a while loop?

So I am carrying out a query and returning the results in the form of a table. The code below works well.
<table>
<thead>
<tr style="text-align: center;">
<th>Activity</th>
<th>Description</th>
<th>Frequency</th>
<th>Mandatory</th>
<th>Added Yet</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $conn->prepare("SELECT * FROM knowledgebase ORDER BY category ASC");
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) echo "<tr><td>No activities found</td><td></td><td></td><td></td><td></td><td></td></tr> </tbody>
</table></br></br>
Why not add your first activity from our Knowledge base or create a new activity of your own";
else {
while($row = mysqli_fetch_array($result)) {
$activity_id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$frequency = $row['frequency'];
$mandatory = $row['mandatory'];
echo "<tr><td>".$title."</td><td>".$description."</td><td style=\"text-align: center;\">".$frequency."</td><td style=\"text-align: center;\">".$mandatory."</td><td></td></tr>";
}
}
$stmt->close();
?>
</tbody>
</table>
What I want to add in is another query inside the final <td></td>. What I want to do is query a second db table and say if this activity has already been added to the users table, echo YES, otherwise, echo NO.
The problems is, adding the query into the while loop keeps throwing errors.
Any suggestions gratefully received.
Instead of running another query for every row, you could join the users table to the knowledgebase table in your first query. If you use a left join, you'll still get all the rows from knowledgebase.
SELECT knowledgebase.*, userstable.activity_id
FROM knowledgebase
LEFT JOIN userstable ON knowledgebase.id = userstable.activity_id
ORDER BY category ASC
Then in your last <td>, you can print YES/NO depending on whether or not there was a matching row in the users table.
...<td><?php echo $row['activity_id'] ? 'YES' : 'NO' ?></td>...
(I made up names for your other table and column, but I think it shows the general idea.)

How to remove duplication in the retrieval results?

Please i need a help am beginner in php and my sql, i want to retrieve all students names who registered in each level(1 OR 2 OR 3 OR 4) this is my code.
<form id="form1" name="form1" method="post" action="">
<table border="1" align="center" class="tftable">
<?php
$lvlid = $_GET['id'];
$sql2 = "select * from `course` where acadlevel='$lvlid' ";
$res2= mysql_query($sql2,$con_mark_entry);
while($row2 = mysql_fetch_row($res2))
{?>
<?php } ?>
<tr>
<th id="h7">Serial NO.</th>
<th id="h7">Student NO.</th>
<th id="h7">Student Name</th>
</tr>
<?php
$s=1;
$sql ="SELECT student.stud_id,student.stud_name, course.title, enrollment.grade FROM student, course, enrollment WHERE course.acadlevel ='".$_GET['id'] ."' AND course.code = enrollment.code AND student.stud_id = enrollment.stud_id";
$res= mysql_query($sql,$con_mark_entry);
while($row1 = mysql_fetch_row($res)){
?>
<tr>
<td><?php echo $s?> </td>
<td><?php echo $row1[0]?></td>
<td id="name"><a href="report6.php?id=<?php echo $row1[1]?>"> <?php echo $row1[1]?> </td>
</tr>
<?php
$s++;
}
?>
</table>
My Problem is for example if the student registered in three course at level 1 ,he would appear three times, i want to remove this duplication. HOW?
The result as follow:
serial no student no student name
1 101 adam nagdy
2 101 adam nagdy
3 101 adam nagdy
4 102 shima najm
Thanks in advance
Use DISTINCT keyword. It removes duplicate result rows.
Search for "distinct" in this page.
SELECT DISTINCT std.stud_id,std.stud_name, enr.grade -- , crs.title
FROM student std
LEFT OUTER JOIN enrollment enr ON std.stud_id = enr.stud_id
LEFT OUTER JOIN course crs ON crs.code = enr.code
WHERE course.acadlevel ='YOUR_ID'
And use JOIN to join. ;) It is better than joining with WHERE (even if it works).
Try using GROUP BY course.acadlevel at the end of your query.
That should reduce the results to one row per academic level, instead of 3, if the student registered for 3 classes.
Also, as John Conde has commented, mysql_ prefixed functions are deprecated and will be removed from future versions of PHP. You should instead use Mysqli or PDO_MySQL. And you should never use $_GET[]/$_POST or any other variables with user input in your MySQL queries without sanitizing them.

Display MySQL table ( number of rows are not same ) in PHP

I have one MySQL table and it has two columns -
I want to display in my site like this -
I can easily take the table name Boy | Girl . But when i try to display the table I get like this -
I am just showing one example here. There may be 50 boys and 10 girls.. So I need help.
After displaying the heading
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
So many views but not getting any answer. Please help guys. Please catch my mistake.
Try with two queries.
Make an array for each category(Male & Female)
It Works.
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".#$males[$i]."</td><td>".#$females[$i]."</td></tr>";
}
Try this query 100% working but set php code.
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM
(SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
Is your problem to do with the creation of the table using PHP or is it related to the SQL query itself?
If it is the creation of the table then I suggest you use two tables embedded in a single table like this. That way you can build the first table using one SQL query, then build the second table using a second query, then display the table and girls and boys will appear side by side regardless of how many entries on each side. Your code would look a bit like this:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
If you need to cater for more categories, do an initial search to determine the distinct categories, then put the section of code above that creates the inner table in a loop.
eg. in pseudo code:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table

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