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
Related
I'm still in the process of learning SQL queries. I've tried searching around online, but I don't even know what terms I should be searching for, so I'm looking for someone to point me in the right direction. I have two tables -- appointments and logins. I'm trying to use the concat function to get the first and last name for both "apptFor" and "addedBy." Do I need to have separate queries? It seems like it should be able to get done in a single query.
<table border="1">
<tbody>
<tr>
<td width="140" align="center"><strong>Appt Date/Time</strong></td>
<td width="100" align="center"><strong>Appt For</strong></td>
<td width="300" align="center"><strong>Appointment</strong></td>
<td width="100" align="center"><strong>Added By</strong></td>
<td width="100" align="center"><strong>Date Added</strong></td>
</tr>
<?php
$query = "SELECT a.appID,a.appDate,a.appNote,a.apptFor,a.addedBy,a.added,concat(u.firstName,' ',u.lastName) as appAddedBy FROM appointments a ";
$query .=" INNER JOIN logins u on a.addedBy=u.userid WHERE a.userID='$uid' order by appDate asc";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $row['appDate']; ?></td>
<td><?php echo $row['apptFor']; ?></td>
<td><?php echo $row['appNote']; ?></td>
<td><?php echo $row['appAddedBy']; ?></td>
<td><?php echo $row['added']; ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
If you need tow name you should join two time the logins
$query = "SELECT a.appID,a.appDate,a.appNote,a.apptFor,a.addedBy
,a.added,concat(u1.firstName,' ',u1.lastName) as appAddedBy
,concat(u2.firstName,' ',u2.lastName) as appApptFor
FROM appointments a ";
$query .=" INNER JOIN logins u1 on a.addedBy=u1.userid";
$query .=" INNER JOIN logins u2 on a.apptFor=u2.userid
WHERE a.userID='$uid' ";
order by appDate asc";
$result = mysqli_query($con, $query);
My code receives a brand from an html form, it then proceeds to generate the search results from the database.
if(isset($_GET['brand'])) {
$brand = mysqli_real_escape_string($db, $_GET['brand']);
echo $brand;
$featuredSql = "SELECT t.*, s.quantity, s.rrp AS nRetailPrice, r.city AS city_name, ts.thumbnail as tread_thumbnail, ts.bigpic as tread_bigpic, t.rating FROM tyres t INNER JOIN stocklevels s
ON t.stockcode=s.stockcode LEFT JOIN tyre_treads ts ON t.treadid=ts.recid LEFT JOIN reseller r ON s.city=r.recid WHERE s.quantity>0 ";
if ($brand != 'Any') $featuredSql .= " AND t.manufacturer='$brand'";
$featuredSql .= "GROUP BY t.diam,t.manufacturer, t.width";
if (!$featured = mysqli_query($db, $featuredSql)) die(mysqli_error());
var_dump($featured);
if (!$tyre1 = mysqli_fetch_object($featured)) echo "<br />No tyres match those parameters. Please try again.";
}
The HTML to represent the data once collected.
<div class="text text-background">
<h4>
<?= $product["profile"] . "/" . $product["width"] . "/" . $product["diam"] . " " . $product['manufacturer']; ?>
</h4>
<p class="brand"><?= $product["part_no"]; ?></p>
<div class="col-md-12 col-sm-12 col-xs-12 text-right">
<div class="txtprice-small">PRICE FROM $<span><?= $product["nRetailPrice"]; ?></span></div>
</div>
<table class="table table-condensed small">
<tbody>
<tr>
<td width="40%">SIZE:</td>
<td width="60%"><?= $product["diam"]; ?></td>
</tr>
<tr>
<td>Width:</td>
<td><?= $product["width"]; ?></td>
</tr>
<tr>
<td>Profile:</td>
<td><?= $product["profile"]; ?></td>
</tr>
<tr>
<td>Stock:</td>
<td><?= $product["quantity"]; ?></td>
</tr>
<tr>
<td>Rating:</td>
<td><?= $product["rating"] ?></td>
</tr>
</tbody>
</table>
if ($brand != 'Any') $featuredSql .= " AND t.manufacturer='$brand'";
$featuredSql .= "GROUP BY t.diam,t.manufacturer, t.width";
if (!$featured = mysqli_query($db, $featuredSql)) die(mysqli_error());
var_dump($featured);
if (!$tyre1 = mysqli_fetch_object($featured)) echo "<br />No tyres match those parameters. Please try again.";
}
Now the problem is the database is poorly maintained and several items are duplicates (hence the GROUP BY diam, manufacturer and width) but each of those items has its own stock, eg
Item part_no abc stock 5,
Item part_no abc stock 7
so there are actually 12, but are both listed as separate items,the GROUP_BY groups them together, but doesn't do anything with the stock level.
My question is how should I handle this? I've looked at trying to use COUNT in the original Query, but the while loop with the fetch assoc breaks if I do that. Although I could have coded it incorrectly (fairly new to PHP and using MySQL).
I could also GROUP BY part_no but this doesn't seem to help either.
Additional Information as recommended
Tyre's Database
RecID is Unique Primary Key
part_no Not Unique
stockCode IS UNIQUE
Sample Data
\/65\/14-4015","thumbnail":null,"bigpic":null,"rating":"82H","tread":null,"profile":"65","width":"175","diam":"14","description":null,"rrp":"0.00","flag":null,"notes":"","treadid":"707","hide":"no","quantity":"1","nRetailPrice":"79.00","city_name":"New Plymouth","tread_thumbnail":"707_thumb.jpg","tread_bigpic":"707_large.jpg"},
{"recid":"3705","part_no":"ALT185\/65\/14","manufacturer":"ALTENZO","supplier":null,"stockcode":"TY-ALT185\/65\/14-3705","thumbnail":null,"bigpic":null,"rating":"86H","tread":null,"profile":"65","width":"185","diam":"14","description":null,"rrp":"0.00","flag":null,"notes":"","treadid":"707","hide":"no","quantity":"1","nRetailPrice":"79.00","city_name":"Palmerston North","tread_thumbnail":"707_thumb.jpg","tread_bigpic":"707_large.jpg"},
{"recid":"4557","part_no":"ALT185\/60\/15","manufacturer":"Altenzo","supplier":null,"stockcode":"TY-ALT185\/60\/15-4557","thumbnail":null,"bigpic":null,"rating":"88H","tread":null,"profile":"60","width":"185","diam":"15","description":null,"rrp":"0.00","flag":null,"notes":"","treadid":"707","hide":"no","quantity":"2","nRetailPrice":"99.00","city_name":"Petone","tread_thumbnail":"707_thumb.jpg","tread_bigpic":"707_large.jpg"},
{"recid":"2827","part_no":"ALT195\/50\/15","manufacturer":"ALTENZO","supplier":null,"stockcode":"TY-ALT195
I have 4 tables:
Users
Forums
Discussies (discussions)
Forumberichten (messages)
The table Forumberichten (messages) contains the id's of the Discussion (discussions) table as a reference to reactions on a discussion. If there are 5 reactions to a discussion, there are 5 id's in the table with the same value.
How do I display an echo of one discussion of every different discussion with the latest reaction on it?
I've tried ORDER BY, DISTICT, GROUP BY and other things but I can't get it to work. I keep getting more outputs of the same discussion or one discussion with the original input and not the latest reaction to it.
<?php
// DISCUSSIES FORUM SCHRIJVEN
$sql="SELECT forumberichten.discussieid,forumberichten.datum,discussies.discussieid,discussies.titel,discussies.forumid,discussies.highlight,forums.forumid,forums.forumnaam,users.userid,users.userimage,users.username FROM forumberichten,discussies,forums,users WHERE forumberichten.discussieid=discussies.discussieid AND discussies.forumid=forums.forumid AND forumberichten.userid=users.userid AND forums.forumid=1 ORDER BY forumberichten.bericht_id DESC LIMIT 3";
$result = $conn->query($sql) or die ("The query could not be completed. try again");
if ($result->num_rows > 0) {
echo "
<br>
<table id='forumschrijvenklein'>
<tbody>
<tr>
<td bgcolor='#1E1E1E'></td>
<td nowrap bgcolor='#1E1E1E'> </td>
<td nowrap bgcolor='#1E1E1E' class='sterrenkleur'>Discussie</td>
<td nowrap bgcolor='#1E1E1E' class='sterrenkleur'>Laatste reactie</td>
<td nowrap bgcolor='#1E1E1E' class='sterrenkleur'>Datum</td>
<td nowrap bgcolor='#1E1E1E' class='sterrenkleur'></td>
</tr>
";
// output data of each row
while ($row = $result->fetch_assoc()) {
echo"
<tr>";if ($row["highlight"] == '1') {
echo " <td bgcolor='#FC6'></td>";
} else {
echo "<td bgcolor='#1E1E1E'></td>";
}
echo"
<td nowrap bgcolor='#1E1E1E'>";if ($row["userimage"] == '') {
echo "
<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/nopicture.png' alt='nopicture' class='userimage-tooltip-small' title='".$row['username']."''></a>";
} else {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/".$row['userimage']."' class='userimage-tooltip-small' title='".$row['username']."''></a>";
}
echo"</td>
<td bgcolor='#1E1E1E'><a href='discussie.php? id=" . $row['discussieid'] . "'>".$row["titel"]."</a></td>
<td bgcolor='#1E1E1E'><a href='user.php? id=" . $row['userid'] . "'</a>".$row["username"]."</a></td>
<td nowrap bgcolor='#1E1E1E'>"; echo date("d-m-y H:i",strtotime($row["datum"]));"
";
echo"
</td>
<td nowrap bgcolor='#1E1E1E'></td>
</tr>
";
}
}
echo "
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='315' height='2'></td>
<td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='140' height='2'></td>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'> </td>
</tr>
</tbody>
</table>
";
}
?>
I tried the following, but it still doesn't work...:
$sql = "SELECT *
FROM (((forumberichten
JOIN discussies
ON discussies.discussieid = forumberichten.discussieid)
JOIN users
ON users.userid = forumberichten.userid)
JOIN forums
ON forums.forumid=forumberichten.forumid)
GROUP BY discussies.discussieid
HAVING forumberichten.forumid = 3 AND forumberichten.bericht_id = max(forumberichten.bericht_id)
ORDER BY forumberichten.bericht_id DESC";
We want the newest post on each unique thread, we can do that by...
Using GROUP BY and HAVING.
SELECT *
FROM Posts
JOIN Discussions
on Discussions.discussion_id = Posts.discussion_id
GROUP BY Discussions.discussion_id
HAVING Posts.post_time = max(Posts.post_time)
ORDER BY Posts.post_time DESC
This is an example! Make sure you use it to modify your own, it's quite simple though. I don't have a database to test this, but I am tested with my own data and different columns and it worked.
Note: This assumes that each Id is identical in both tables. It also assumes that post_time is some time value that increases the more recent the post is (i.e. SQL Timestamp).
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
My code
<?php
include('ConnectToDb.php');
$query = "SELECT * FROM News WHERE NewsFlag = 1 ORDER BY PostDate DESC";
$arrCount = -1;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$ID=$row['ID'];
$PostDate = $row['PostDate'];
$NewsHeader = stripslashes($row['NewsHeader'])
;
$NewsStart = stripslashes($row['NewsStart'])
;
echo "<hr>";
echo "<div>". date('j F Y',strtotime($PostDate)). "</div>";
echo "<p>";
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
if(count($array)>0) {
echo "<img src='". $array[0]. "' alt='' />";
}
echo "<h2 style='text-align:center'><u><a href='latestnews_full.php?ID=$ID'>". $NewsHeader. "</a></u></h2>";
echo "<div style='text-align:left'><h3>";
echo $NewsStart. " ......<a href='latestnews_full.php?ID=$ID'>(more)</a><br />";
echo "<div style='text-align:center'>";
echo "</div>";
echo "</h3></div>";
}
?>
displays my data nicely on four lines with date at the top, then a picture, title and then description.
However, I want to display the data as a table like this
<table style="width: 100%">
<tr>
<td colspan="2">postDate here</td>
</tr>
<tr>
<td rowspan="2">picture here</td>
<td>newsHeader here</td>
</tr>
<tr>
<td>newsStart here</td>
</tr>
</table>
I'm not sure how to echo the table cells correctly and all of my attempts so far have resulted in a white page. Could anyone please enlighten me?
I'd suggest you to make your logic separated from your presentable part. Close the PHP tag once you are ready fetching the results, assigning var's etc, then:
<table style="width: 100%">
<?php
//yourcode
//...
//...
$NewsStart = stripslashes($row['NewsStart']);
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
?>
<tr>
<td colspan="2"><?= date('j F Y',strtotime($PostDate)) ?></td>
</tr>
<tr>
<?php
if(count($array)>0) {
?>
<td rowspan="2"><img src='<?= $array[0] ?>' alt='' /></td>
<?php } ?>
<td><?= $NewsHeader ?></td>
</tr>
<tr>
<td><?= $NewsStart ?> </td>
</tr>
<?php } ?>
</table>
However, it's again not so clear, and I would suggest using a template engine. If you want I can post a code with assigning vars to Smarty and output your presentation in Smarty template