COUNT a number of database rows affiliated with an id - php

I'm creating a forum and right now I am trying to figure out how to count the number of replies in a topic. I am wanting to count the number of rows per topic_id #. So if there is a topic id of 5 and there are 10 rows in my database of topic_id #5, I want the it to count and output 10.
I tried to structure my query like this
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id) AS tid2 FROM forum_topics AS t, forum_posts AS p ORDER BY topic_reply_date DESC")
All this did however was mess up my original query which was this...
$query2 = mysqli_query($con,"SELECT * FROM forum_topics WHERE `category_id` ='".$cid."' ORDER BY topic_reply_date DESC")
And it is now only showing 1 topic rather than the 15 I have and it it outputting a very large Count figure of 406.
How can I get the following code to only count the topic_id associated with the topic that is being outputted and still allow for all of my topics to be outputted?
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id) AS tid2 FROM forum_topics AS t, forum_posts AS p ORDER BY topic_reply_date DESC")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
//if ( false===$query2 ) {
// die(' Query2 failed: ' . htmlspecialchars($query2->error));
//}
if($numrows2 > 0){
$topics .= "<table width='100%' style='border-collapse: collapse;'>";
//Change link once discussion page is made
$topics .= "<tr><td colspan='3'><a href='discussions.php'>Return to Discussion Index</a>".$logged."<hr /></td></tr>";
$topics .= "<tr style='background-color: #dddddd;'><td>Topic Title</td><td width='65' align='center'>Replies</td><td width='65'
align='center'>Views</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row = mysqli_fetch_assoc($query2)){
$tid = $row['id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$replies = $row['tid2'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
$topics .= "<tr><td><a href='forum_view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator." on ".$date."</span></td><td align='cener'>".$replies."</td><td align='center'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
}

Use GROUP BY clause (tutorial):
SELECT t.*, COUNT(p.topic_id) AS tid2
FROM forum_topics AS t JOIN forum_posts AS p on t.id = p.topic_id
GROUP BY t.id
Also note that OUTER JOIN is used in my example (instead of CROSS JOIN in your example).

Related

Adding a second database table to a query and outputting a column that has the same name as another

I have the following query below and I am having a hard time figuring out the best way to add in a database table to it. I want to be able to add the table forum_categories to it and just select the id from that. I'm not sure how to have two of the same column names in a query, but that is the only field I need from that table.
How can I add forum_categories to this query..
$query2 = mysqli_query($con,"SELECT * FROM forum_topics ORDER BY topic_reply_date DESC LIMIT 3")
And then fetch only the id from it and be able to output it with having the same column name?
<?php
$con = mysqli_connect("localhost", "", "", "");
$query2 = mysqli_query($con,"SELECT * FROM forum_topics ORDER BY topic_reply_date DESC LIMIT 3")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
if($numrows2 > 0){
$topics .= "<table width='100%' style='border-collapse: collapse;'>";
//Change link once discussion page is made
$topics .= "<tr style='background-color: #dddddd;'><td>Topic Title</td><td width='65' align='center'>Replies</td><td width='65'
align='center'>Views</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row2 = mysqli_fetch_assoc($query2)){
$tid = $row2['id'];
$title = $row2['topic_title'];
$views = $row2['topic_views'];
$date = $row2['topic_date'];
$creator = $row2['topic_creator'];
$topics .= "<tr><td><a href='forum_view_topic.php?tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator." on ".$date."</span></td><td align='cener'>0</td><td align='center'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
}
$topics .="</table>";
echo $topics;
} else {
echo "<p>There are no topics in this category yet.</p>";
}
?>
Here is your corrected SQL query:
SELECT t.*, c.id AS cid FROM forum_topics AS t, forum_categories AS c ORDER BY t.topic_reply_date DESC LIMIT 3

List Results in a Table - While Loop and List Results in TD Also

I have tried to find the answer for this but having no joy. I have a while loop that gives me numerous rows outputted in a table. It's here:
$result = mysqli_query($con,"SELECT a.winner AS horseWinner, a.twitter_pubstatus,
a.market, a.racetime, a.racecourse, a.date_dd, a.date_mm, b.username, b.course,
b.horse,b.type, b.racetime, b.dd, b.mm FROM results a
INNER JOIN bets b ON a.winner = b.horse WHERE a.twitter_pubstatus = 0
AND a.market = '$win' AND b.type = '$userwin'
AND a.date_dd = b.dd AND a.date_mm = b.mm GROUP BY a.winner");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['horseWinner'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "</table>";
This is all well and good but the issue lies that there is more than one username that is per horseWinner. I have tried to do another while loop within a while loop. So I would like it to list the usernames in the second column seperated by comma.
Many thanks
Add a GROUP_CONCAT() on your username so that it returns a comma separated list -
SELECT a.winner AS horseWinner, a.twitter_pubstatus,
a.market, a.racetime, a.racecourse, a.date_dd, a.date_mm,
GROUP_CONCAT(b.username) as username,
b.course, b.horse,b.type, b.racetime, b.dd, b.mm FROM results a
INNER JOIN bets b ON a.winner = b.horse WHERE a.twitter_pubstatus = 0
AND a.market = '$win' AND b.type = '$userwin'
AND a.date_dd = b.dd AND a.date_mm = b.mm GROUP BY a.winner

Working with output from joined tables with php oop

As part of my learning OOP PHP, I have made a database object that includes the following method:
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = static::instantiate($row);
}
return $object_array;
}
and I can use this to retrieve and access data from a single table, however when I try to use it with joined tables, the object only gives me the data from the primary table e.g.
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
Using the above query the following code outputs nothing for the s.name field, but all the fields from the members table are correctly listed. I know that the MySQL query is accessing the data, as the ORDER BY statement is correctly sorting the output.
<?php foreach($members as $member): ?>
<tr>
<td><?php echo $member->name;?></td>
<td><?php echo $member->full_name();?></td>
<td><?php echo $member->getAge($member->dob);?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
If I output $members with print_r($members) it only contains the data from the members table, how do I access the data retrieved from the other tables?
Thanks
You need to select them too here:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
You only selected name, id, firstName, lastName and dob.
Here is an example:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob, mbr_sections.field_you_want, sections.*";

php table warning : Invalid argument supplied for foreach

I want to output a 5 column table based on the query below , the output on phpmyadmin is correct but I am getting error :
Invalid argument supplied for foreach() on the php page. Any help would be highly appreciated. Thanks
code :
<?php
$database =& JFactory::getDBO();
//Declare Variables
$user = JFactory::getUser();
$id = $user->get('id');
$name = $user->get('name');
// Display quizzes
echo "</br>";
echo "Quizzes History for : " ;
echo "<b>";
echo $name;
echo "</b>";
echo "</br>";
echo "</br>";
$database->setQuery(" SELECT distinct qui.title AS name,
( SELECT GROUP_CONCAT(profiles.title)
FROM jos_jquarks_users_profiles AS users_profiles
LEFT JOIN jos_jquarks_profiles AS profiles ON users_profiles.profile_id = profiles.id
WHERE users_profiles.user_id = sessionWho.user_id ) AS profile,
( SELECT sum(score)
FROM jos_jquarks_quizzes_answersessions
WHERE quizsession_id = quizSession.id AND status <> -1 ) AS score,
( SELECT count(distinct question_id) FROM jos_jquarks_quizzes_answersessions
WHERE quizsession_id = quizSession.id ) AS maxScore,
DATE_FORMAT(quizSession.finished_on,'%M %d, %Y') AS FinishedOn
FROM jos_jquarks_quizsession AS quizSession
LEFT JOIN jos_jquarks_users_quizzes AS users_quizzes ON users_quizzes.id = quizSession.affected_id
LEFT JOIN jos_jquarks_quizzes AS qui ON users_quizzes.quiz_id = qui.id
LEFT JOIN jos_jquarks_quizzes_answersessions AS quizSessAns ON quizSessAns.quizsession_id = quizSession.id
LEFT JOIN jos_jquarks_sessionwho AS sessionWho ON sessionWho.session_id = quizSession.id
LEFT JOIN jos_jquarks_users_profiles AS users_profiles ON users_profiles.user_id = sessionWho.user_id
LEFT JOIN jos_jquarks_profiles AS profiles ON profiles.id = users_profiles.profile_id
WHERE sessionWho.user_id = ' .$id " ) ;
if (!$database->query()) { //write data and if error occurs alert
echo "<script> alert('".$database->getErrorMsg()."'); </script>";
}
//var_dump($database);
$tableStyle = "padding: 5px;border:1px";
$tdStyle = "padding:5px ";
$thStyle = "padding:7px ";
echo '<table style="' . $tableStyle . '" cellpadding="7" cellspacing="7">';
echo "<tr> <th style=align:center>Quiz Title </th><th style=align:center> Score </th><th>Maximum Score </th><th> Unanswered </th> <th>Finished On </th></tr>";
$row = $database->loadRowList();
foreach($row as $valuearray)
{
echo '<tr style=" align="center">';
foreach($valuearray as $field)
{
echo "<td>$field</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This typically means that there is an error in your query, and it's not returning any results so there is no object to run through the foreach. The easiest way to debug this is to turn on debug mode from the joomla administrator panel (it's in global settings -> system), and then going to the page this error is being thrown, and it should show the SQL error.
Anyway, looking at the query the only error I can find (assuming all fields/tables are correct) is that at the end you have:
WHERE sessionWho.user_id = ' .$id " ) ;
This should be:
WHERE sessionWho.user_id = $id " ) ;
or
WHERE sessionWho.user_id = ". intval($id) ) ;

GET variable after doing a Join Query

For the code below, on the second link (http://www...com/sandbox/comments/index.php?submission='.$row["title"].'), I would like to pass $row["submissionid"], on as a GET variable. I tried this and it caused all of the code below to produce a blank result. Is there a way that I can do I want?
Thanks in advance,
John
$sqlStr = "SELECT
s.loginid
,s.title
,s.url
,s.displayurl
,l.username
,COUNT(c.commentid) countComments
FROM
submission s
INNER
JOIN
login l
ON
s.loginid = l.loginid
LEFT OUTER
JOIN
comment c
ON
s.submissionid = c.submissionid
GROUP
BY
s.submissionid
ORDER
BY
s.datesubmitted DESC
LIMIT
10";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"samplesrec\">";
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td class="sitename1">'.$row["title"].'</td>';
echo '</tr>';
echo '<tr>';
echo '<td class="sitename2">'.$row["username"].''.$row["countComments"].'</td>';
echo '</tr>';
}
echo "</table>";
Add submissionid to your select.

Categories