My code join 4 table using INNER JOIN. I can't customize loop while using inner join. How to control while clause so unwanted loop wouldn't happen.
My code output (student and school name is looping in every subject field)
I want to display like this where student and school loops at once.
MY PHP Code
<table id="customers">
<?php
$query=$con->prepare("SELECT subjectcomb.subjectid, subjectcomb.schoolid, student.student, school.school, subject.name
FROM ((( subjectcomb
INNER JOIN school ON subjectcomb.schoolid=school.id)
INNER JOIN student ON subjectcomb.schoolid=student.schoolID)
INNER JOIN subject ON subjectcomb.subjectid=subject.id)");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)){?>
<tr>
<td>
<?php echo $row['school']."->".$row['student']?>
</td>
</tr>
<tr>
<td>
<?php echo $row['name']?>
<input type="text" name="mark"></input>
</td>
</tr>
<?php } ?>
</table>
Try adding an ORDER BY to your query:
$query=$con->prepare("SELECT subjectcomb.subjectid, subjectcomb.schoolid, student.student, school.school, subject.name
FROM ((( subjectcomb
INNER JOIN school ON subjectcomb.schoolid=school.id)
INNER JOIN student ON subjectcomb.schoolid=student.schoolID)
INNER JOIN subject ON subjectcomb.subjectid=subject.id)
ORDER BY school.school, student.student");
then in the while loop use this check:
<?php
$last_student = ""
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
if ($last_student != $row['student']) {
?>
<tr>
<td>
<?php echo $row['school']."->".$row['student']?>
</td>
</tr>
<?php } ?>
<tr>
<td>
<?php echo $row['name']?>
<input type="text" name="mark"></input>
</td>
</tr>
<?php $last_student = $row['student'] } ?>
I think what Phil meant was something like the following. You keep track of the previous school and student. If the current school and student are the same as the previous, you skip printing the school/student row, but if they not the same, you print them and also update the previous school's and previous student's values.
$prev_school = '';
$prev_student = '';
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['school'] != $prev_school && $row['student'] != $prev_student) { ?>
<tr>
<td>
<?php echo $row['school']."->".$row['student'] ?>
</td>
</tr>
<?php
$prev_school = $row['school'];
$prev_student = $row['student'];
}
?>
<tr>
<td>
<?php echo $row['name']?>
<input type="text" name="mark"></input>
</td>
</tr>
<?php
}
Related
I have two tables ie abstract table and author with one to many relation, for each iteration on while loop I want to display a html table of unique row of data from abstract table with corresponding rows from author table.
This what I did:
public function getAll() {
try {
$sql = " SELECT tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content,
tbl_author.afirst_name, tbl_author.alast_name,
tbl_author.aaffilition
FROM tbl_abstract
INNER JOIN tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
GROUP BY tbl_abstract.abstract_id";
$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<table class="table" >
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?>. <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].' '.$row["last_name"]; ?>,
//data from tbl_author
<?php echo $row["afirst_name"].' '.$row["alast_name"];?>
</td>
</tr>
<tr>
<td align="center" ">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
</table>
<?php
}
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
There are three records from tbl_author associated with the abstract_id from tbl_abstract but i only get one record instead of 3 of them.Please help
Try this one :-
<?php
$sql = "SELECT *
FROM tbl_abstract
where abstract_id IN (SELECT distinct abstract_id
FROM tbl_abstract)";
$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
?>
<table class="table" >
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?> <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].' '.$row["last_name"]; ?>,
<?php
$sql1 = "SELECT *
FROM tbl_author
WHERE abstract_id = '".$row["abstract_id"]."'" ;
$stmt1= $this->pdo->prepare($sql1);
$stmt1->execute();
while($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){
//data from tbl_author
echo $row1["afirst_name"].' '.$row1["alast_name"];
} ?>
</td>
<td align="center">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
<?php } ?>
</table>
Try removing the GROUP BY clause like this:
SELECT
tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content, tbl_author.afirst_name,
tbl_author.alast_name, tbl_author.aaffilition
FROM
tbl_abstract
INNER JOIN
tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
Group by is grouping all the authors by the field abstract_id, which means, that it won't return all the authors, but only one for one abstract_id (based on the sorting field, which in this case is probably the primary key, because it is not explicitly defined)..
I am working on an election system and I am having difficulty solving a problem. Following is how my application looks like.
At the moment I get these results by adding the query multiple times on my php file. (for example run it where RaceID = 9, RaceID = 10 .........)
I am sure there should be a way of reading the RaceID as an array or some other way and get the results that way. Since these are JOIN tables I am also looking for a way of retrieving the RaceName (Presidential Names, Justice Supreme Court ... etc) and MainRaceName(Titles with red, blue, gray) as well. I hope I am making some sense so far...
Following is my code for
<!-- MAIN ELECTION TICKET MainID loop should control this -->
<div class="panel panel-red margin-bottom-40">
<div class="panel-heading">
<h2 class="panel-title"> <strong>REPUBLICAN NATIONAL</strong> </h2>
</div>
<!-- End then SUB ELECTION TICKET RaceID loop should control this section-->
<h3 style="background-color:#f5f5f5; margin:30px; padding:5px; font-weight:Bold ">Presidential Race </h3>
<!-- Finally Results section ELECTION RESULTS -->
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>Candidate</th>
<th>Votes</th>
<th>%</th>
</tr>
<!-- This area gets the sum of the votes for a specific RaceID -->
<?php
$result = mysql_query('SELECT SUM(CandidateVotes) AS value_sum FROM candidates WHERE RaceID =9');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
?>
</thead>
<tbody>
<?php
$query = "SELECT candidates.CandidateName, candidates.CandidateVotes, candidates.Party, mainrace.MainRaceName, race.RaceName, candidates.win
FROM candidates
JOIN race ON race.RaceID = candidates.RaceID
JOIN mainrace ON mainrace.MainID = candidates.MainID
WHERE candidates.RaceID = 9";
$result = mysql_query($query) or die(mysql_error());
for($i=0; $row = mysql_fetch_array($result); $i++){
?>
<tr>
<!--Show winner Icon if the win field is selected as 1 from database -->
<td width="5px">
<?php if ($row['win']==1)
{
echo "<span class=\"glyphicon glyphicon-check\"></span>";
}
else
{
echo "<span class=\"glyphicon glyphicon-unchecked\" style=\"color:#cccccc\"></span>";
}
?>
</td>
<td><?php if ($row['win']==1){
echo "<strong>";
echo $row['CandidateName'];
echo "</strong>";
}
else {
echo $row['CandidateName'];
}
?>
</td>
<td width="20%"><?php echo $row['CandidateVotes']; ?></td>
<td width="30%"><?php
if ($row['CandidateVotes']>0){
echo number_format((float)(($row['CandidateVotes']/$sum)*100), 2, '.', ''). ' %';
}
else{
echo "N/A";
}
?>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td><strong>Total Votes:</strong></td>
<td><strong><?php echo $sum ?></strong></td>
<td></td>
</tr>
</tbody>
</table>
I really appreciate if you can provide some samples (loops) how I can resolve this problem. Your help is much appreciated. Sincerely,
You should be able to pull down everything you need in one query.
In order to sum up votes by candidate, you need to make sure you GROUP BY the candidate name.
Try something like this:
SELECT
SUM(candidates.CandidateVotes) AS value_sum,
candidates.CandidateName,
candidates.Party,
mainrace.MainRaceName,
race.RaceName,
candidates.win
FROM candidates
JOIN race
ON race.RaceID = candidates.RaceID
JOIN mainrace
ON mainrace.MainID = candidates.MainID
WHERE candidates.RaceID = :raceId
GROUP BY candidates.CandidateName
good day i am building a website for recipes and im trying to display a recipe with multiple ingredients but the ingredients are in a separate table so when i run the query if i have three ingredients the recipe id will appear three times along with the other data because the ingredients column is populated by only one entry...is there anyway to merge these entries?
here is my code and link to an image of how the data is appearing..any help would be great
[img]http://forums.trinituner.com/upload/data/62/all recipes duplicate.jpg[/img]
my code
$db=mysql_select_db("tasteofhome");
$query = "select RECIPES.recipe_ID,RECIPES.recipe_name,RECIPES.recipe_author,RECIPES.cook_time,RECIPES.stages_description, INGREDIENTS.ingredients_name, USERS.user_name from
RECIPES,USERS,RECIPE_INGREDIENTS,INGREDIENTS where USERS.user_ID=RECIPES.user_ID AND
RECIPES.recipe_ID = RECIPE_INGREDIENTS.recipe_ID
AND RECIPE_INGREDIENTS.ingredients_ID = INGREDIENTS.ingredients_ID
";
$result = mysql_query ($query);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while ($rows = mysql_fetch_array ($result))
{ //begin of while loop
?>
<tr>
<td> <?php echo $rows [0]; ?> </td>
<td> <?php echo $rows [1]; ?> </td>
<td> <?php echo $rows [2]; ?> </td>
<td> <?php echo $rows [3]; ?> </td>
<td> <?php echo $rows [4]; ?> </td>
<td> <?php echo $rows [5]; ?> </td>
<td> <?php echo $rows [6]; ?> </td>
</tr>
<?php
} //end of while loop
?>
You could join the recipes and users tables with an aggregate query that uses group_concat to join the ingrediants to a coma-delimited string:
SELECT r.recipe_ID,
r.recipe_name,
r.recipe_author,
r.cook_time,
r.stages_description,
gi.ingredients_names,
u.user_name
FROM RECIPES r
JOIN USERS u ON u.user_ID = r.user_ID
JOIN (SELECT ri.recipe_ID,
GROUP_CONCAT(i.ingredients_name) AS ingredients_names
FROM RECIPE_INGREDIENTS ri
JOIN INGREDIENTS i ON ri.ingredients_ID = i.ingredients_ID
GROUP BY recipe_ID) gi ON gi.recipe_ID = r.recipe_ID
I have three mysql tables subjects, examinations, examinfo
TABLE - SUBJECTS
subjectid
subjectname
subjectExamid
TABLE - EXAMINFO
examid
exam
TABLE EXAMINATIONS
fname
lname
studentid
score
subjectid
ON subject.subjectExamid = exam.examid
ON examination.subjectid = subject.subjectid
Now i would like to generate HTML table indicating scores students get per paper against subject
STRUCTURE TABLE OUTPUT
Student details against each subject score
EDIT CODE SAMPLE
<?php
$examinid = 3;
$subjects = mysqli_query(
$con,"
SELECT * FROM subjects
WHERE examid = '$examinid'
ORDER BY shortname ASC
");
$content = mysqli_query(
$con,"
SELECT DISTINCT exam.idcandidate, exam.sex, exam.fname, exam.lname
FROM examinations
AS exam
INNER JOIN examinfo
AS info
ON exam.id_subject = info.idsubject
WHERE info.idexam = '$examinid'
");
?>
<div id="table_1">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="table1tr">#</td>
<td class="table1tr">Candidate</td>
<td class="table1tr">ID</td>
<td class="table1tr">Sex</td>
<?php
// output subjects
while($subRow = mysqli_fetch_array($subjects)){
$arbv = strtoupper($subRow['shortname']);
$subjectname = ucwords(strtolower($subRow['subjectname']." - ".$subRow['subjectid'].""));
?>
<td class="table1tr" title="<?php echo $subjectname; ?>">
<?php echo $arbv; ?>
</td>
<?php
}
?>
<td class="table1tr">Exam</td>
</tr>
<?php
while($stdnt = mysqli_fetch_array($content)){
$fullname = ucwords(strtolower("$stdnt[lname] $stdnt[fname]"));
$studentid = str_replace(array('/', 'M', 'W', 'S', 'F', '-'), "",$stdnt['idcandidate']);
if($sex = $stdnt['sex'] == Male){
$sex = M;
}else{ $sex = F; }
$id_subject = $stdnt['id_subject'];
$x++;
$zebra_1 = ($x%2)? 'TableZebra_1': 'TableZebra_2';
?>
<tr>
<td class="<?Php echo $zebra_1; ?>"><?php echo $count++; ?></td>
<td class="<?Php echo $zebra_1; ?>"><?Php echo $fullname; ?></td>
<td class="<?Php echo $zebra_1; ?>"><?php echo $studentid; ?></td>
<td class="<?Php echo $zebra_1; ?>"><?php echo $sex; ?></td>
<td class="<?Php echo $zebra_1; ?>">
<!-- Problem is here how to output the subject grades $grade -->
<!--
My first unsuccessful approach
SELECT score
FROM examinations AS test
INNER JOIN examinfo AS testinfo ON testinfo.idsubject = test.id_subject
WHERE testinfo.idexam
IN (
SELECT idexam
FROM examinfo
WHERE idexam = $examinid
)
AND test.id_subject = $id_subject AND test.idcandidate = '$studentid'
Then output results - But this falls it shows one student subjects in one cell
-->
</td>
<td class="<?Php echo $zebra_1; ?>">Exam</td>
</tr>
<?php
} // loop content
?>
</table>
</div>
If your solution is not concat(); you may first
follow the simple steps
1 loop $contents // to get info such as studentid
2 inside the loop of $contents loop $subjects // to get all subjects including subjectids
3 inside $subject loop, loop examinations table where studentid = '$studentid' AND subjectid = '$subjectid'
if step three return null echo empty cell otherwise echo cell with score
I have no time to test this, but you may follow the steps and it will work otherwise try google search
I am done with a CMS school system which i created from scratch for practice in php. My question is for example I have Accounting 101, Computer Science 101, however there must multiple times for Accounting 101. For example: Ticket 1035, 1036 are both Accounting 101 and they should appear in the same table, but in my code it shows them in different classes. Here is my code.
if(isset($_GET['id']))
{
$category = $_GET['id'];
$sql = "SELECT * FROM classes WHERE category_id = " . $category;
$query2 = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($query2))
{
?>
<center><h3><?php echo $row->class_name . '-' . $row->units; ?> </h3></center>
<table border ="0" wdith="100%">
<tr>
<td>
<strong>Description: </strong>
<?php echo $row->class_description; ?>
</tr>
</td>
</table>
<br/>
<table border="1" width="44%">
<tr>
<td width="60"><b>Ticket</b> </td>
<td width="123"><b>Days</b></td>
<td width="120"><b>Hours</b></td>
<td width="64"><b>Room</b></td>
<td><b>Instructor</b></td>
</tr>
<tr>
<td width="60"> <?php echo $row->ticket; ?> </td>
<td width="123"><?php echo $row->days; ?></td>
<td width="120"><?php echo $row->start_hours . $row->time_format . '-' . $row->end_hours . $row->time_format2 ; ?> </td>
<td width="64"> <?php echo $row->room_number; ?></td>
<td><?php echo $row->instructor_name; ?></td>
</tr>
}//end while
}//end if
Its showing Accounting 101 with different tickets in different tables, but it should be all in 1 table. Thanks.
You need a double loop if you're trying to get records inside of records. For example:
while ($row1 = mysql_fetch_object($query1))
{
echo $row1->ParentName;
$query2 = 'select * from `mytable` where `myForeignKey` = ' . $row1->ParentId;
while ($row2 = mysql_fetch_object($query2))
{
echo $row2->ChildName;
}
}
You could also do a left join. Let me know if you need a sample of that.
Edit:
The left join would be done like this:
$sql = "select * from `classes` as a where category_id = '{$category}' left join `tickets` as b on a.id = b.class_id"
Ref. http://www.w3schools.com/sql/sql_join_left.asp