Display data from join? - php

I have a page where it displays a movie review, that is displayed by a link Read Review on this same page I would also like to display the movie title. So do I have to use a join to display the information or is there a simpler way of doing it ? I have tried using a few queries but I end up getting all the film titles for the one review.
This is where the query first starts on the film.php
$query = "SELECT films.movie_title, films.rating, films.actor, reviewed.review,
users.username
FROM films
LEFT JOIN reviewed ON films.movie_id=reviewed.movie_id
LEFT JOIN users ON films.user_id=users.user_id";
$result = mysql_query($query) or die ("Could not execute mysql" . mysql_error());
$num = mysql_num_rows($result);
if ($num > 0) { // If it ran ok, display records.
echo "<p> There are curently $num records.</p>";
// Table header.
echo '<table border="1" align="center" cellspacing="0" cellpadding="5">
<tr>
<td align="left"><b>Movie Title</b></td>
<td align="left"><b>Leading Actor</b></td>
<td align="left"><b>Rating</b></td>
<td align="left"><b>Author</b></td>
<td align="left"><b>Review</b></td>
</tr>';
// Fetch and print all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td align="left">' . $row['movie_title'] . '</td>
<td align="left">' . $row['actor'] . '</td>
<td align="left">' . $row['rating'] . '</td>
<td align="left">' . $row['username'] . '</td>
<td align="left"> Read Review
</tr> ';
}
}
?>
Now on this page is displays the review but I would like to display the movie_title within the sub_review container.
<body>
<div id="sub_review_container">
<?php
?>
</div>
<div id="Review_container">
<?php
$review = $_GET['id'];
echo $review;
?>
</div>
</body>

You are missing the id of the review in the query of which you want to show the review.
Also because of left join. It is showing all records. You should use inner join for reviews and films. It should be like:
$query = "SELECT films.movie_title as movie_title, films.rating, films.actor, reviewed.review, users.username FROM films INNER JOIN reviewed ON films.movie_id=reviewed.movie_id INNER JOIN users ON films.user_id=users.user_id where reviewed.id = ... "
...reviewed.id will be the Id you pass from page.

Related

Get a while loop to run "X" number of times with two conditions in PHP

So i have this code:
<?php
require_once('../../ccconnect.php');
$query = "SELECT * FROM orgs";
$response = #mysqli_query($dbc, $query);
if($response){
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr>
<td align="left"> <b>Logga</b> </td>
<td align="left"> <b>Namn</b> </td>
<td align="left"> <b>Andel till ändamål</b> </td>
<td align="left"> <b>Vinst</b> </td> </tr>';
while($row = mysqli_fetch_array($response))){
echo '<tr>
<td align="left">' . $row['logo'] . '</td>
<td align ="left">' . $row['name'] . '</td>
<td align ="left">' . $row['chare'] . '</td>
<td align ="left">' . $row['profit'] . '</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "Kunde inte genomföra databaskomandot<br>";
echo mysqli_error($dbc);
}
?>
The code will print out a table of results from my database, but i want to limit the results i get to only show 5 results for example. How would i do this?
Use the LIMIT clause in SQL.
SELECT * FROM my_table
LIMIT 5;
https://dev.mysql.com/doc/refman/5.5/en/select.html
http://www.w3schools.com/php/php_mysql_select_limit.asp
You need to limit the query or limit the loop. (I like the first option better).
You have this query:
$query = "SELECT * FROM orgs";
Wanna get 5 results only?
$query = "SELECT * FROM orgs LIMIT 5";

ORDER BY one ID when there are more of the same ID's in one table

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

How to display multiple rows one after the other repeating a sequence depending on how many rows I get?

My idea is to create a Q&A section under a product profile, just like on eBay or Amazon or whatever. The idea is to send a question and then get the owner of the article to reply.
The table has these columns: pid (product ID), id (question ID), question, answer, date (date posted), username.
So if I post a question, I get the ID of the product in which I'm posting and create a question. The the owner just sends the answer to the row that matches the question.
Here's my PHP code to retrieve all the info from that table:
$qanda = '';
$link = mysql_connect("localhost", "youknowwhat", "youknowwhat");
mysql_select_db("youknowwhat", $link);
$qandaq = mysql_query("SELECT * FROM questions WHERE id='$id2' ORDER BY date", $link);
$count = mysql_num_rows($qandaq);
if($count >= 1){
while($rows = mysql_fetch_array($qandaq)){
$date = $rows['date'];
$q = $rows['question'];
$a = $rows['answer'];
$usrname = $rows['username'];
}
$qanda .= '<div id="answers" align="center">
<table cellspacing="0" align="center">
<tr align="center">
<td width="200">' . $date . '</td>
<td rowspan="2" width="400"><strong>' . $q . '</strong><br>' . $a . '</td>
<td width="200">Delete</td>
</tr>
<tr align="center">
<td>' . $usrname . '</td>
<td>Report</td>
</tr>
</table>
</div>';
} else {
$qanda = '<div id="answers" align="center">
No questions for this product.
</div>';
}
Now... what you see as a table in the variable $qanda I want to repeat it over and over again but displaying different row data but the concatenation isn't working and I can only get the last row to be displayed. I just can't seem to find out why this isn't working! Am I missing something?
All you have to do is append your divs (.=) while you're inside the while loop that mysql_fetch_array() rows.
Then you'll have a new div for each row your database returns, and you can populate it easily.
$qanda = '';
while($rows = mysql_fetch_array($qandaq)){
$date = $rows['date'];
$q = $rows['question'];
$a = $rows['answer'];
$usrname = $rows['username'];
$qanda .= '<div id="answers" align="center">
<table cellspacing="0" align="center">
<tr align="center">
<td width="200">' . $date . '</td>
<td rowspan="2" width="400"><strong>' . $q . '</strong><br>' . $a . '</td>
<td width="200">Delete</td>
</tr>
<tr align="center">
<td>' . $usrname . '</td>
<td>Report</td>
</tr>
</table>
</div>';
}

How do I pass values with a link to a new page?

What I want is to be able to click on the link (review.php) and then to display the review corresponding to that film only, on a new page.
Not sure if my MySQL query is wrong or if my A href link is not formatted correctly.
Any help would be appreciated.
require_once('./includes/mysql_connect.php');
$query = "SELECT films.movie_title, films.rating, films.actor, reviewed.review
FROM films
INNER JOIN reviewed
ON films.movie_id=reviewed.review_id";
$result = mysql_query($query) or die ("Could not execute mysql" . mysql_error()); // Run Query
$num = mysql_numrows($result);
if ($num > 0) { // If it ran ok, display records.
echo "<p> There are curently $num records.</p>";
// Table header.
echo '<table border="1" align="center" cellspacing="0" cellpadding="5">
<tr>
<td align="left"><b>Movie Title</b></td>
<td align="left"><b>Leading Actor</b></td>
<td align="left"><b>Rating</b></td>
<td align="left"><b>Review</b></td>
</tr>';
// Fetch and print all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td align="left">' . $row['movie_title'] . '</td>
<td align="left">' . $row['actor'] . '</td>
<td align="left">' . $row['rating'] . '</td>
<td align="left"><a href="review.php?id='. $row['review'] . '> Read Review </a>
</tr> ';
}
}
?>

grouping class names together in my CMS php

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

Categories