MYSQL join query not working - php

I have 2 mysql tables named
blog
comment
What i am trying to do to retrieve following columns
user_name comment_desc from the comment table using blog_id.
Both the tables have blog_id in common.
here below are the screenshots of both sql tables
Comment Table:
Blog Table:
I tried the query this way.
SELECT blog.blog_id, comment.user_name, comment.comment_desc
FROM
blog (b)
INNER JOIN
comment (c)
ON b.blog_id = c.blog_id
i dont have access to upload the image thats why i uploaded to photobucket.
The PHP Code....
<?php
$comments_set = blog_comments();
var_dump($comments_set);
while($comments_all = mysql_fetch_assoc($comments_set)){
$name = $comments_all['user_name'];
$desc = $comments_all['comment_desc'];
echo
"<ol class=\"commentlist clearfix\">
<li class=\"comment even thread-even depth-1\" id=\"li-comment-1\">
<div id=\"comment-1\" class=\"comment-wrap clearfix\">
<div class=\"comment-meta\">
<div class=\"comment-author vcard\">
<span class=\"comment-avatar clearfix\">
<img alt='' src='http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=60' class='avatar avatar-60 photo avatar-default' height='60' width='60' /></span>
</div>
</div>
<div class=\"comment-content clearfix\">
<div class=\"comment-author\">$name<span>January 24, 2013 at 10:46 am · <a class='comment-reply-link' href=\"#\">Reply</a></span></div>
<p>$desc</p>
</div>
</div>
</li>
</ol>
";
}
?>

You need user_name and desc from comment table with blog_ig
Why you need to join these 2 tables then ? you could retrieve information from comment table by blog id
select * from comments where blog_id='blog_id'

You are using alias so at the time of SELECT statement, specify it through alias name. You need to remove parenthesis around alias name...
SELECT b.blog_id, c.user_name, c.comment_desc
FROM
blog b
INNER JOIN
comment c
ON b.blog_id = c.blog_id

I think you have incorrectly define the blog_id columns. Please check columns' datatype and sizes.
It will fail when joining tables.
If you can paste error it will be more helpful
Thanks.

I think you should go for Left Join because may be you want to have blogs to be displayed whether they have comments or not.
SELECT b.blog_id, c.user_name, c.comment_desc
FROM
blog as b
LEFT JOIN
comment as c
ON b.blog_id = c.blog_id

Related

how to show separate column unique values with SQL GROUP BY clause

Alright, I can't bash my head at this anymore tonight. Thought I would pose the question. Maybe there's a simple answer I have not come across yet.
I have a number of related tables in PHPMyAdmin: pubtopics, pubtypes, and pubtitles.
Pubtitles is the main table (table 1), pubtopics is a simple list assigning a number to a topic (table 2), and pubtypes is another simple list assigning a number to a publication type (table 3).
I'm trying to create a page that lists every publication by type (list of all pubs in table 3), but also shows the multiple topics (table 2) that may be assigned to a unique pubtitle (table 1), and have each of those topics (table 2) link to publications listed by that topic.
The data for pubtopics looks something like this:
pubtopics
What I'm looking for is a line like this:
June 15, 2016 | Comparative Data Report | Education | Fiscal Affairs
Where the date is a link, the pub type is a link, and each of the concatenated issues is a unique link.
When I try to list all the publications for a specific publication type, all I can generate so far is either a list with multiple duplicate entries (because one may address several topics). I've tried group_concat and group by, but that doesn't allow me to have an individual link for each topic.
I've played around with explode and arrays, but it's a bit beyond my know-how. Any brilliant solutions?
Code looks like:
elseif (isset($_GET['type'])) {
$var3_getDisplay4 = $_GET['type'];
$query_getDisplay = sprintf("SELECT
DATE_FORMAT(publicationsnew.date, '%%Y') AS archive,
DATE_FORMAT(publicationsnew.date, '%%M %%e, %%Y') AS pubdate,
pub_type.number AS typelink,
pub_type.type AS pubtype,
GROUP_CONCAT(categories.category_name ORDER BY categories.category_name SEPARATOR ' | ') AS category,
categories.category_id AS catlink,
publicationsnew.title,
publicationsnew.author,
publicationsnew.imagelink,
publicationsnew.description
FROM
pub_cat
LEFT JOIN publicationsnew ON (pub_cat.pub_id = publicationsnew.pub_id)
LEFT JOIN categories ON (pub_cat.category_id = categories.category_id)
LEFT JOIN pub_type ON (publicationsnew.type = pub_type.number)
WHERE pub_type.number = %s
GROUP BY publicationsnew.pub_id
ORDER BY publicationsnew.date DESC",
GetSQLValueString($var3_getDisplay4, "text"));
and in the body:
<?php do { ?>
<h2><?php echo $row_getDisplay['pubdate']; ?> | <?php echo $row_getDisplay['pubtype']; ?> |
<a href="test.php?topic=<?php echo $row_getDisplay['catlink']; ?>">
<?php echo $row_getDisplay['category']; ?>
</a>
</h2>
<p class="pubtitle"><?php echo $row_getDisplay['title']; ?></p>
<?php echo ($row_getDisplay['author']); ?>
<?php echo ($row_getDisplay['imagelink']); ?>
<div class="pubdescription"><?php echo ($row_getDisplay['description']); ?></div>
<div class="clear"></div>
<hr>
<?php } while ($row_getDisplay = mysql_fetch_assoc($getDisplay)); ?>
Burned out for the day. To be continued...

Website querys advanced

I am building website like social network.
And i made 3 tables: users, posts, and friends.
How can I write code to display posts from me and from my friends:
Users: id, email, username, password, image
Posts: id, pid, pname, ppost, pimage
Friends: id, user1, user2, friends(yes or no)
So i need to check if user1 is $_SESSION[user] , than too check every row with friends as yes and than echo every post from user1(me) and other users who are friend of mine.
I made some code but it echo posts only from me and first user i marked as friend, i can't show posts from other users i marked as friend.
Users: id:1 email:email#email.com, username:test, password:xd , image:This is link
Users: id:2 , email: test#email.com, username:test2, password:xd, image:Link
Users: id:3 , email: test2#email.com, username:test3, password:xd, image:Link
Posts: id:1 , pid(this is publisher id):etc 1,2,3 , pname:Name of publisher , ppost:Text , pimage: image of publisher:
So just imagine i have 3 posts from 3 diferent users
Friends: id:(auto)1,2,3,4 , user1(user1 is session user) if i login to first user it will be 1, user2(id of other user like 2(test2)), friends(yes)
Friends: id:(auto)1,2,3,4 , user1(user1 is session user) if i login to first user it will be 1, user2(id of other user like 3(test3)), friends(yes)
So i need to echo posts from users(me) , and two others and every other user which have friends(yes) , and don't show posts from users which are marked no.
I made this so far: Querys:
`session_start();
$res=mysql_query("SELECT * FROM users WHERE id=".$_SESSION['user']);
$row=mysql_fetch_array($res);
$res2=mysql_query("SELECT * FROM posts WHERE pid=".$_SESSION['user']);
$row2=mysql_fetch_array($res2);
$res3=mysql_query("SELECT * FROM obavijesti");
$row3=mysql_fetch_array($res3);
$res5=mysql_query("SELECT user1, user2 FROM osobe WHERE friends='yes' AND user1='$_SESSION[user]' order by id limit 5000");
$row5=mysql_fetch_array($res5);
$user2=$row5['user2'];
$user1=$_SESSION['user'];
`
PHP script:
<?php $result = mysql_query("SELECT * FROM posts WHERE pid='$user1' OR pid='$user2' order by id desc limit 5000") ?>
<div class="publishcontent">
<link rel="stylesheet" type="text/css" href="testt.css">
<div class="posts">
<article class="post">
<header class="post-header"><span class="post-user-name"><?php echo $row4['pname']; ?></span><span class="post-header-posted">Objavljeno: Danas</span></header>
<div class="post-flex-container">
<aside class="post-user">
<image src="<?php echo $row4['pimage']; ?>" class="post-user-image"></image>
<div class="post-user-status is-online">TEST</div>
<div class="post-user-posts">Broj objava: x</div>
<div class="post-user-joined"><?php if($row['spol'] == "zensko" ) {
echo "Pridružila se";
}
else {
echo "Pridružio se";
} ?> : <?php echo $row['date']; ?></div>
</aside>
<section class="post-content">
<p>
<?php echo htmlspecialchars($row4['ppost']); ?>
</p>
</section>
</div>
</article>
</div>
</div>
<?php endwhile ?>
And it only displays posts from me and first person i marked as friend, but don't show posts from third person
I would go back to your mysql and refactor your database schema. Your Users table will need to have a one to many relationship with user_id in your Friends table. And your Users table will also need to have a one to many relationship with friend_id in the Friends table. (this allows you to store the user_id of the friend and the user_id of the befriended.) The users table will also have a one to many relationship with the Posts table. Then Change Your mysql to use an inner join query. The inner join query will allow you to query all the results from each table with one query. Here is a link to learn more about that. http://www.w3schools.com/sql/sql_join_inner.asp
SELECT users.*, friends.*, posts.* FROM users INNER JOIN friends ON users.id = friends.user_id INNER JOIN posts ON users.id = posts.user_id
Also you can add a WHERE clause at the end of the query to get related posts and friends for the current logged in user

Mysql query returning too many rows

so I have 3 tables all inner joined, I am trying to put discussions with the discussion topic on my main page, with the users name and the latest discussion message on the main page as well.
THE PROBLEM: The query is returning all messages attached to all the discussions.....I just need the last message associated with the discussion returned.
I have been at this all day and cant figure it out. I have tried group by but that just gave me an error on mysqli_fetch_array
Here is my code
$discussionquery = "SELECT discussion_messages.discussion_id, user_profile.first_name, user_profile.last_name, discussion_messages.message_text, case_discussion.discussion_title
FROM `user_profile`
INNER JOIN discussion_messages
ON (user_profile.user_id = discussion_messages.user_id)
INNER JOIN case_discussion
ON (case_discussion.discussion_id = discussion_messages.discussion_id)
WHERE discussion_messages.case_id = '$thecaseid'
ORDER BY discussion_messages.message_id DESC";
$discussionquerydata = mysqli_query($dbc, $discussionquery);
while ($row2 = mysqli_fetch_array($discussionquerydata)) {
$discussion_id = $row2['discussion_id'];
?>
<!-- Begin Recent Discussions -->
<div class="row">
<a href="discussion.php?newfact=$thecaseid'>">
<div class="col-xs-4 col-md-2">
<img src="img/client4.jpg" class="profile_picture img-rounded">
<?php echo '<h6 class="discussionname">' . $row2['first_name'] . ' ' . $row2['last_name'] . '</h6>';?>
</div>
</a>
<div class="col-xs-8 col-md-10 discussion_title">
<?php echo '<h5> '.$row2['discussion_title'].' -'. $row2['message_text'];?></h5>
<h6 class="pull-right">Dec. 25</h6>
</div>
</div>
<?php
};
You need logic to find the last message for each discussion. There is more than one way to write this condition.
The following does it using a not exists clause. This checks that there are no messages with a larger id for the discussion:
SELECT dm.discussion_id, up.first_name, up.last_name, dm.message_text, cd.discussion_title
FROM `user_profile` up INNER JOIN
discussion_messages dm
ON (user_profile.user_id = dm.user_id) INNER JOIN
case_discussion cd
ON (cd.discussion_id = dm.discussion_id)
WHERE dm.case_id = '$thecaseid' and
not exists (select 1
from discussion_messages dm2
where dm2.discussion_id = dm.discussion_id and
dm2.message_id > dm.message_id
)
ORDER BY dm.message_id DESC;
One suggestion, use table aliases. The amount of total code will be smaller and easier to understand. Use the limit clause to return 1 row.
$discussionquery = "
SELECT
m.discussion_id,
u.first_name,
u.last_name,
d.message_text,
c.discussion_title
FROM `user_profile` as u
INNER JOIN discussion_messages as m
ON (u.user_id = m.user_id)
INNER JOIN case_discussion c
ON (m.discussion_id = c.discussion_id)
WHERE
m.case_id = '$thecaseid'
ORDER BY
m.message_id DESC
LIMIT 1";

PHP MySQL get data from 2 tables

I am trying to combine 2 tables from my database:
files table:
id
file_name
file_description
file_url
access_files table:
id
student_id
file_id
Here is my sql code, currently getting all files from the files table, it doesn`t show the selected files for the user.
<?php
$SQL = "SELECT * FROM files, access_files WHERE student_id ='$studentid'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
?>
<div class="accordion-group">
<div class="accordion-heading">
<a href="#<?php print $db_field['file_id']; ?>" data-parent="#accordion" data-toggle="collapse" class="accordion-toggle collapsed">
<?php print $db_field['file_name']; ?>
</a>
</div>
<div class="accordion-body collapse in" id="<?php print $db_field['file_id']; ?>">
<div class="accordion-inner">
<?php print $db_field['file_description']; ?><br/><br/>
Download File Now!
<br/><br/>
</div>
</div>
</div>
<?php } ?>
The code is suppose to show only the files associated to the user.
What you need to do is JOIN the tables.
Most common types of JOINs:
INNER JOIN - Used to match data where it can match the ON () statement. If the ON() doesn't match, the result will be excluded.
LEFT JOIN - Used if the data you match in the ON() doesn't have to be there. It just appends the data to the original FROM, and fills columns with NULL if no data is matched.
Example
SELECT
ft.id,
ft.file_name,
ft.file_description,
ft.file_url,
af.id as access_id,
af.student_id,
af.file_id
FROM
files ft
INNER JOIN access_files af ON ( ft.id = af.file_id )
WHERE
fa.student_id = '$studentid'
You are making a classic cartesian join with your query:
SELECT * FROM files, access_files WHERE student_id ='$studentid'
You need to specify how the two tables are connected:
SELECT * FROM files a, access_files b WHERE a.student_id ='$studentid' and b.studentID=a.student_id
If you don't specify the link - or don't have one, the database will try to link every single row in the first table with every single row in the second.
Join your tables.
SELECT table1.*, table2.*
FROM table1
LEFT JOIN table1.pk = table2.fk
WHERE table1.pk = 1;

How to display all comments per article (PHP & SQL)?

So I have two tables, article and comments (which has one-to-many relationship (1 article - many comments)). This is how the table is structured:
Articles - id (prikey), title, publicationDate, content
Comments - com_id (prikey), author, comment, id (foreign key)
I used this to query the two tables:
SELECT * FROM articles as a INNER JOIN comments as c ON a.id = c.id
Previously, I was only displaying the articles table using this:
<?php
while($row = mysqli_fetch_array($query)) {
echo "
<div id='article'>
<header>
<hgroup>
<h2>".$row['title']."</h2>
<h4>Posted on ".$row['publicationDate']."</h4>
</hgroup>
</header><p>".$row['content']."</p></div>";
}
?>
This displays all articles (with date, title, content, etc.). Now there are comments. How do I edit the php code (or if my query is incorrect, how to write the query), so that it shows all articles and all comments per article as in:
Article One
-- Comment 1
-- Comment 2, etc.
Article Two
-- Comment 1
-- Comment 2, etc.
An alternative would be to split the query into two.
The first would bring back the articles you want...
SELECT * FROM article;
Once you have those, you can get all the IDs and use something like the following
SELECT * FROM comments WHERE article_id IN (".$list.");
This restricts the MySQL queries to 2 whilst getting all the data you need. After this loop around the article data, and in that loop, loop around the comments data.
This also means that, unlike using GROUP_CONCAT, you will also have author data to use.
It's not a very eloquent solution, but should work.
Query:
SELECT c.author, c.comment,
a.id article_id, a.title, a.publicationDate, a.content
FROM comments c
RIGHT JOIN articles a
ON c.id = a.id
PHP:
<?php
$lastArticleId = 0;
$isNewArticle = false;
while($row = mysqli_fetch_array($query)) {
$isNewArticle = ($lastArticleId != $row['article_id']) ? true : false;
if($isNewArticle) {
$lastArticleId = $row['article_id']; ?>
<div class="article">
<header>
<hgroup>
<h2><?php echo $row['title']; ?></h2>
<h4>Posted on <?php echo $row['publicationDate']; ?></h4>
</hgroup>
</header>
<p><?php echo $row['content']; ?></p>
</div>
<?php
}
if($row['comment'] != '') { ?>
<p><strong><?php echo $row['author']; ?></strong> - <?php echo $row['comment']; ?></p>
<?php
} ?>
<?php
} ?>
Use something like
SELECT a.article
,GROUP_CONCAT(CONCAT('<p>', c.comment, '</p>') SEPARATOR "\n") as comments
FROM
article a
INNER JOIN comment c ON (c.article_id = a.id)
WHERE a.id = '12454';
You may have to fiddle a bit with the separator.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Do note however:
The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:
SET [GLOBAL | SESSION] group_concat_max_len = val;
See here how to change max_allowed_packet
http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_max_allowed_packet
Look into MySQL GROUP_CONCAT which will return a comma delimited list of items. You can then explode that for your comments section.
once a person will comment on a article insert article id with that comment and later get them accordingly something like this
once a person will select an article to read send article id in the $_GET to your article page so you can excess the article id.Once a person will comment on that article insert it as follows
$sql = mysql_query("INSERT INTO comments_table (subject,article_id,comments) VALUES ('$subject','$_GET['id']','$comments')");
and later when you pulling them do it the same way as you have the article id in the $_GET
you can access it run a query like this
$fetch = mysql_query("SELECT * FROM comments WHERE article_id = $_GET['id'] ORDER BY id DESC") or die(mysql_error());
Hope this will work

Categories