I dont know where to start let me make it simple...
I have 2 tables posts and comments, posts consisting 2 fields: id and post_name and comments consisting of 3 fields: id, comment and post_id. I have some posts with few comments on those.
How can I display all posts with the related comments using while loop?
Thanks in advance....
SELECT `p`.`post_name`, `c`.`comment`
FROM `posts` AS `p`
JOIN `comments` AS `c` ON(`p`.`id` = `c`.`post_id`)
GROUP BY `p`.`id`;
This will give you a resultset where each row contains a comment and the name of the post that goes with that comment.
You'll need a nested loop to accomplish what you are looking for. Here's a sample that should help get you started.
$posts_result = mysql_query("SELECT your, columns FROM poststable");
if(mysql_num_rows($posts_result) > 0){
$comments_result = mysql_query("SELECT comments FROM commentstable WHERE comments.post_id = $post_id");
while($post = mysql_fetch_array($posts_result){
// print post details
if(mysql_num_rows($comments_result) > 0){
while($comment = mysql_fetch_array($comments_result)) {
// print comment details
}
} else {
// print comments default for when there are no comments
}
} // End posts while
} else {
// print no posts found
}
Run query
select * from posts p, comments c where p.id=c.post_id group by p.id;
and iterate over the results and display them as you want.
This should get you started:
$sql = 'SELECT c.*, p.post_name FROM posts p INNER JOIN comments c ON p.id = c.post_id ORDER BY p.id DESC, c.post_id DESC';
$result = mysql_query($sql);
$previous_post = 0;
while ($data = mysql_fetch_assoc($result)) {
if ($previous_post != $data['post_id']) {
echo '<h1>' . $data['post_name'] . '</h1>';
$previous_post = $data['post_id'];
}
echo '<p>' . $data['comment'] . '</p>';
}
Related
I have my table from post , post_id, admin_id,content,date_created,status while table comment , post_id, admin_id, content, date_posted, status. so how can notification specifically.
----this is my sample sql query that i made.-----
$result= mysql_query("SELECT admin_id from comment inner join post on post.post_id = comment.post_id where comment.status = 1 AND post.post_id = comment.post_id");
$row= mysql_fetch_array ($result);
$id=$row['admin_id'];
$commentcount = mysql_result(mysql_query("SELECT COUNT(*) from comment inner join post on post.post_id = comment.post_id where comment.status = 1 AND post.admin_id = $id"),0);
if ($id == $id_session) {
echo $commentcount;
}
else {
//echo $postcount;
}
i am looking forward to hear from you guys. i am a student/new member on this so please keep your answer as simple as possible. thank you.
I am building a simple newspaper-site, due to schoolwork. I have two tables in my database.
Categories
[CategoryID, CategoryName, ParentID (which points to cat.id)]
Article
[ArticleID, Heading, Teasertext, Content, Date, Category(which is foreign key to CategoryID)]
On the first page im pulling out the latest articles written, and below each article has to have a link to the article (which is based on index.php?name=CategoryName&parent=ParentID).
I need to withdraw the relevant info about CategoryName and ParentID from the Category-info in Articles-table.
Im stuck on how to combine the two queries in to one. Im wondering if you have any idea´s on how to solve it?
This is what I got.
function display_articles($link)
{
$result = mysqli_query($link, "SELECT * FROM Article ORDER BY Date DESC");
if (!$result)
{
$error = 'Error fetching Articles: ' . mysqli_error($link);
exit();
}
while ($row = mysqli_fetch_array($result))
{
$Heading[] = $row['Heading'];
$Teasertext[] = $row['Teasertext'];
$Date[] = $row['Date'];
}
if (isset($Heading))
{
for ($i=0; $i<count($Heading); $i++)
{
echo '<div class="frontpage"><h2>' .htmlspecialchars($Heading[$i], ENT_QUOTES, "UTF-8"). '</h2>';
echo htmlspecialchars($Date[$i], ENT_QUOTES, "UTF-8");
echo '<p class="Teasertext"> ' .htmlspecialchars($Teasertext[$i], ENT_QUOTES, "UTF-8"). '</p></div>';
echo '<a href="index.php?name='
}
}
}
Use a join:
SELECT
a.*, c.CategoryName, c.ParentID
FROM
Article AS a
INNER JOIN Category AS c on a.category = c.categoryId
ORDER BY a.Date DESC
Your query should be like this:
SELECT
a.*,c.*
FROM
Article a LEFT JOIN
Categories c on (a.category=c.categoryid)
ORDER BY
a.Date DESC
I have this snippet that shows all taxonomy list in the site, that belongs to a specific vocabulary.
Instead of printing the whole list, how do I just print the terms that belong to the node I'm actually loading?
I have a Drupal 7 installation.
This is how I print the id of the node I´m at: <?php print $node->nid;?>
<?php
$vid = 11; //vocabulary id
$query = "SELECT tid, name, count
FROM (
SELECT td.tid AS tid, name, COUNT(td.tid) AS count
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
ON td.tid = tn.tid
JOIN node AS n
ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
AND n.status = 1
GROUP BY td.tid
ORDER BY count DESC
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
if ($term->count > 0) {
echo l($term->name, "taxonomy/term/$term->tid").' ('.$term->count.')'.'<br/>';
}
}
?>
I would suggest not to run extra query for this.
This information should be available in $node object.
Just print it [print_r($node) ] and see what exactly is the taxonomy object name($node->taxonomy) & how taxonomy information is structured & use that to display category on node page or node teaser.
On other pages, you can use node_load to 1st load the node and then do the same thing.
sumoand's answer is more optimal in this case, however for some sql practicing here's the exact solution the way you imagined:
<?php
$vid = 11; //vocabulary id
$query = "SELECT tid, name, count
FROM (
SELECT td.tid AS tid, name, COUNT(td.tid) AS count
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
ON td.tid = tn.tid
JOIN node AS n
ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
AND n.status = 1
AND n.nid = ".$node->id."
GROUP BY td.tid
ORDER BY count DESC
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
if ($term->count > 0) {
echo l($term->name, "taxonomy/term/$term->tid").' ('.$term->count.')'.'<br/>';
}
}
?>
I have two tables called categories and topics.
categories has columns category_id and category_title. topics has columns topic_id, topic_title, and category_id.
I currently display the columns like so:
$result = mysqli_query($db_server, 'SELECT c.category_title, t.topic_title FROM categories c JOIN topics t on c.category_id = t.category_id');
while ($row = mysqli_fetch_array($result))
{
$category_title[] = $row['category_title'];
$topic_title[] = $row['topic_title'];
}
<?php
foreach ($category_title as $category_title):
echo htmlspecialchars($category_title, ENT_QUOTES, 'UTF-8');?><br />
<?php endforeach; ?>
<?php
foreach ($topic_title as $topic_title):
echo htmlspecialchars($topic_title, ENT_QUOTES, 'UTF-8');?><br />
<?php endforeach; ?>
This will display as:
Category 1
Category 1
Category 2
Topic 1
Topic 2
Topic 3
Topic 1 and 2 are assigned to Category 1, while Topic 3 is assign to Category 2.
How can I have Category display once if there are multiple topics assign to it, such as:
Category 1
Category 2
Topic 1
Topic 2
Topic 3
Please no classes and objects examples. I'm not learning that yet.
You can run query two time first for category then run new query to selected topic according to category as below:
<?php
$result = mysqli_query($db_server, 'SELECT c.category_id,c.category_title FROM categories as c');
$recordArray=array();
while ($row = mysqli_fetch_array($result))
{
$category_id = $row['category_id'];
$recordArray[$category_id] = $row['category_title'];
//Query For Topic
$getTopic = mysqli_query($db_server, "SELECT t.topic_title FROM topics as t WHERE t.category_id='".$category_id."'");
while ($getRow = mysqli_fetch_array($getTopic))
{
$recordArray[$category_id]['topic'][] = $getRow['topic_title'];
}
}
print"<pre>";
print_r($recordArray);
?>
Use group_concat, here is an example http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
You can modify your SQL query adding a "GROUP BY" statement. It would be something like:
SELECT c.category_title, t.topic_title FROM categories c JOIN topics t on c.category_id = t.category_id GROUP BY c.category_id
You can find here a clear example of using GROUP BY.
written off my head not tested:
first I dunno why don't you use it inside one loop, it will perform faster but it will swap the output
$result = mysqli_query($db_server, 'SELECT c.category_title, t.topic_title FROM categories c JOIN topics t on c.category_id = t.category_id');
$oldCategory='';
while ($row = mysqli_fetch_array($result)) {
if ($oldCategory!=$row['category_title']) {
echo htmlspecialchars($row['category_title'], ENT_QUOTES, 'UTF-8').'<br />';
$oldCategory=$row['category_title'];
}
echo htmlspecialchars($row['topic_title'], ENT_QUOTES, 'UTF-8').'<br />';
}
or this will not swap the output:
$result = mysqli_query($db_server, 'SELECT c.category_title, t.topic_title FROM categories c JOIN topics t on c.category_id = t.category_id');
$oldCategory='';
$catStr='';
$topStr='';
while ($row = mysqli_fetch_array($result)) {
if ($oldCategory!=$row['category_title']) {
$catStr.=htmlspecialchars($row['category_title'], ENT_QUOTES,'UTF-8').'<br />';
$oldCategory=$row['category_title'];
}
$topStr.=htmlspecialchars($row['topic_title'], ENT_QUOTES, 'UTF-8').'<br />';
}
echo $catStr.$topStr;
I have the following table:
Comments
--------
id PK
cid
content
uid
comment
If the content is image /i want it to print ?imgID=$cid and get the data from the row title from the table images and if it's a thread I want it to print ?threadID=$cid and get the title from the table threads and so on. How should I do this?
<h3>Latest comments</h3>
<?php
$rs = mysql_query("
SELECT *
FROM comments
LEFT JOIN threads
ON threads.id = comments.cid
WHERE comments.uid = $id
");
while ($row = mysql_fetch_assoc($rs)) {
echo $row['title'];
}
while ($row = mysql_fetch_assoc($rs)) {
if($row['content'] == "image") {
echo "?imgID={$cid}";
$title = mysql_fetch_assoc(mysql_query("SELECT title from images WHERE id = '$cid'");
} elseif ($row['content'] == "thread") {
echo "?threadID={$cid}";
$title = $row['title']; // Will only work as long as there is no title field in comments, oherwise use threads.title
}
}
echo $title;
There you go. The curly brackets around the $cid aren't strictly nessecary, but they help avoid issues where if you are trying to print text afterwards, and it reads the variable name as something else.
$q="SELECT c.id, c.cid, c.content, c.uid, c.comment,
COALESCE(t.title,i.title) AS the_title
FROM comments c LEFT JOIN threads t ON (c.cid=t.id AND c.content='thread')
LEFT JOIN images i ON (c.cid=i.id AND c.content='image');
The above combines your two queries together and puts the title attribute in one column.