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.
Related
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.
I have a table that consist of records and i want to retrieve rows with minimum price. I try the code below, and i am only able to retrieve only one rows. i need to return all rows with minimum price for the same partno.
<tr>
<th>S/N</th>
<th>Part Number</th>
<th>Description </th>
<th nowrap="nowrap">Recommended Price</th>
<th nowrap="nowrap">Recommended Supplier</th>
</tr>
<?php
$get = mysqli_query($con,"SELECT MIN(price)As price,partno,supplier,description FROM tab_stockqty2 ");
$c=0;
while($rw = mysqli_fetch_array($get)){
$c++;?>
<tr>
<td nowrap="nowrap"><?php echo $c;?></td>
<td nowrap="nowrap"><?php echo $rw['partno'];?></td>
<td nowrap="nowrap"><?php echo $rw['description'];?></td>
<td><?php echo number_format($rw['price'],2);?></td>
<td><?php echo $rw['supplier'];?></td>
</tr>
<?php };?>
See Database Record:
It show return two rows, but it is only retuning only one row for the first set of partno-2070081
To retrieve all records with minimal price, per partno, the query should be something like this:
SELECT s.price,s.partno,s.supplier,s.description FROM tab_stockqty2 s
INNER JOIN (
SELECT MIN(price) as m, partno FROM tab_stockqty2 GROUP BY 2
) m on s.price = m.m and s.partno = m.partno
Demo: http://sqlfiddle.com/#!9/3e089/1
try this ==>
SELECT MIN(price)As price,partno,supplier,description FROM tab_stockqty2 group by partno
The SQL MIN returns only 1 row which is the most minimum.
What you can do is fetch all records and sort them on price based on ascending order.
SELECT price,partno,supplier,description FROM tab_stockqty2 ORDER BY price ASC;
Try this instead.
In this way you will get records based on price from Low to High.
For my current progress I need to create a table like the one below
pid cid eid name value
1 1 4 name ab
2 1 5 amt 2
3 1 4 name cd
4 1 5 amt 4
Instead of creating the table like this
pid cid name amt
1 1 ab 22
2 1 cd 4
Anyhow created table as my wish with the below code
<table width="1204" height="100" border="1">
<tr>
<?php $sqlname="Select * From elements where cat_id='1' order by e_id ";
$resname=mysql_query($sqlname);
while($rowname=mysql_fetch_array($resname)){
?>
<td colspan="2"><?php echo $rowname['lable_name']; ?></td>
</tr>
<tr>
<?php $i=0;
$sqlprolist="select value from products_list where name='".$rowname['lable_name']."' and e_id='".$rowname['e_id']."'";
$resprolist=mysql_query($sqlprolist);
while($rowprolist=mysql_fetch_array($resprolist)){
$i++;
?>
<td><?php echo $rowprolist['value'];?></td>
<?php if($i%8==0){
?>
<tr></tr>
<?php }?>
<?php }?>
</tr>
<?php }?>
</table>
But I don't have any idea to retrieve data from the table for processing.
thanks
as by following martin the table created as like the below table
pid cid eid name value
12 1 4 name abc
1 1 4 name cde
13 1 5 code 12
2 1 5 code 14
how to split up the data
like
name code breeder quality size
abc 12 121 121 22
acfd 34 164 22 22
thanks
It's difficult to help you without seeing database structure. Please share it with us, you might get better answers.
Anyway, I suppose you have two tables, elements and products_list. It looks like you need to lookup the value column in the products_list for every row in the elements table. You can merge these table into one result set using a single SQL query:
SELECT e.p_id, e.cat_id, e.e_id, e.lable_name, p.value
FROM elements e, products_list p
WHERE e.cat_id='1' AND
p.name = e.lable_name AND p.e_id = e.e_id
ORDER BY by e.e_id
Note that the e.p_id is just a guess, you have not shared with us, where the "pid" column value gets from. Also not sure, if you actually need to match the rows using the p.name = e.lable_name. If e_id is primary key, you might do with p.e_id = e.e_id only.
What's the point of cid column? If it is indeed the cat_id column in database, why do you need it in HTML table, if you filter the elements to cat_id=1 anyway? Was that intentional?
You can now take the results of the query and simply output it to a HTML table row by row like:
<table width="1204" height="100" border="1">
<tr>
<th>pid</th>
<th>cid</th>
<th>eid</th>
<th>name</th>
<th>value</th>
</tr>
<?php
$sqlname =
"SELECT e.p_id, e.cat_id, e.e_id, e.lable_name, p.value ".
"FROM elements e, products_list p ".
"WHERE e.cat_id='1' AND ".
"p.name = e.lable_name AND p.e_id = e.e_id".
"ORDER BY e.e_id";
$resname = mysql_query($sqlname);
while ($row = mysql_fetch_array($resname))
{
?>
<tr>
<td><?php echo $row['p_id'];?></td>
<td><?php echo $row['cat_id'];?></td>
<td><?php echo $row['e_id'];?></td>
<td><?php echo htmlspecialchars($row['lable_name']);?></td>
<td><?php echo $row['value'];?></td>
</tr>
<?php
}
?>
</table>
This is just a first step. It's unlikely this is correct answer. But I hope it helps you understand, what are you trying to do and to your question.
This is hardly production-grade code. But I wanted to do as little changes as possible, so you can see, what is the actual change from your code.
Also note that the mysql_ functions are deprecated. See the big red box on PHP documentation page.
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.
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