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
Related
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...
I have an artist page that is supposed to show the albums released by a particular artist.
I am joining two tables to accomplish this. The relation is the artist_name. Both the artist table and the albums tables have different IDs.
Unfortunately, the artist page is showing ALL of the album photos in the database instead of only the ones related to the artist.
My thought process was to to use the $_GET method to grab the artist name which would be included in the URL when the user clicks the link to visit that artist's page. But obviously, this is not working.
Here's my script:
$artist_name = $_GET['artist_name'];
//Query the database to show the albums
$albums = "SELECT artist.artist_name,albums.artist_name,albums.photo,albums.album_title
FROM artist,albums
WHERE artist.artist_name=albums.artist_name
ORDER BY year_released ASC";
$q = $db->query($albums);
$q->setFetchMode(PDO::FETCH_ASSOC);
html:
<?php while ($r = $q->fetch()): ?>
<span class="margin-two album">
<img src="http://mywebsite.com/albums/<?php echo $r['photo']; ?>" alt="picture of the album <?php echo $r['album_title']; ?> by <?php echo $r['artist_name']; ?>" title="<?php echo $r['album_title']; ?>" \>
</span>
<?php endwhile; ?>
How can I output the correct albums for each artist?
Use below query with left join to albums table.
$artist_name = $_GET['artist_name'];
//Query the database to show the albums
$albums = "SELECT artist.artist_name,albums.artist_name,albums.photo,albums.album_title
FROM artist,albums
LEFT JOIN
albums on albums.artist_name = artist.artist_name
WHERE artist.artist_name=$artist_name
ORDER BY year_released ASC";
$q = $db->query($albums);
$q->setFetchMode(PDO::FETCH_ASSOC);
Let me know if you have any question.
Change your $albums string to :
$albums = "SELECT artist.artist_name, albums.photo, albums.album_title
FROM artist
LEFT JOIN albums ON (artist.artist_name=albums.artist_name)
WHERE artist.artist_name=$artist_name
ORDER BY year_released ASC";
Thanks to everyone for pointing me in the right direction with MYSQL LEFT JOIN. After doing a bit more research, I got the following code to work by adding USING in my script.
$artist_name = $_GET['artist_name'];
//Query the database to show the albums
$albums = "SELECT * FROM artist
LEFT JOIN albums
USING (artist_name)
WHERE artist_name='$artist_name'
ORDER BY year_released";
I am sure I am missing something obvious or the mySQL code I have written for this tool is incorrect.
What I have got is a site that allow people to follow each other. If they are following a user they should see updates from them in their user dashboard.
I have had to tie several tables together in mySQL query to get the relevant information.
Here are the tables
users
ID Username Password
-------------|---------------|------------------
1 User1 UserPass
2 User2 UserPass
3 User3 UserPass
user_details
ID UserID UserPhoto
-------------|---------------|------------------
1 1 User1photo.jpg
2 2 User2photo.jpg
3 3 User3photo.jpg
userstatusposts
UserStatusID UserID status
-------------|---------------|------------------
1 1 Hey My first post
2 2 Woah this is cool
3 3 It doesnt work
followers
followid followerUserID beingFollowedUserID
-------------|---------------|------------------
1 3 1
There are more cols and rows in these tables but this is a basic form for the question.
As you can see from the followers table User3 is following User1 and should therefore be able to see the posts they have made in userstatusposts, the reason user details and users also need tying in is so I can display the users photo and the users username
The SQL I have at the moment that isn't working is:
SELECT * FROM userstatusposts
JOIN followers ON userstatusposts.userid = followers.followeruserid
JOIN users ON userstatusposts.userid = users.id
JOIN user_details ON userstatusposts.userid = user_details.userid
WHERE followers.beingFollowedUserID='$userid'
ORDER BY userstatusposts.userstatusid DESC
LIMIT 10
However this is all tied together wrong as I see the posts of the wrong users when it is implemented in to my PHP code ($userid is the logged in user).
PHP Page:
<?php
$sql = "SELECT * FROM userstatusposts
JOIN followers ON userstatusposts.userid = followers.followeruserid
JOIN users ON userstatusposts.userid = users.id
JOIN user_details ON userstatusposts.userid = user_details.userid
WHERE followers.beingFollowedUserID='$userid'
ORDER BY userstatusposts.userstatusid DESC
LIMIT 10
";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
if ($rowcount === 0) {
echo '<li style="list-style-type: none;"><p>Your not currently folllowing anyone.</p></li>';
} else {
while($row = $result->fetch_assoc()) {
if ($row['posttype'] == 'message') {
echo '<li style="list-style-type: none;"><img src="userimg/'.$row['userphoto'].'" height="90px" width="90px"><h3>'.$row['username'].'</h3><small>17/06/2014</small><p>'.$row['status'].'</p></li>';
}
else if ($row['posttype'] == 'map') {
echo '<li style="list-style-type: none;"><img src="userimg/'.$row['userphoto'].'" height="90px" width="90px"><h3>'.$row['username'].'</h3><p>has recently added <b>'.$row['status'].'</b> to there travel map</p></li>';
}
else if ($row['posttype'] == 'like') {
echo '<li style="list-style-type: none;"><img src="userimg/'.$row['userphoto'].'" height="90px" width="90px"><h3>'.$row['username'].'</h3><p>has recently liked a trip report called <b>'.$row['status'].'</b></p></li>';
}
else if ($row['posttype'] == 'report') {
echo '<li style="list-style-type: none;"><img src="userimg/'.$row['userphoto'].'" height="90px" width="90px"><h3>'.$row['username'].'</h3><p>has recently shared a trip report called <b>'.$row['status'].'</b></p></li>';
}
else {
echo 'We are currently expirencing a few diffculties';
}
}
}
?>
I am aware there are other cols being used here but they are in the tables listed above I have just left them out for the question.
Any suggestions why my SQL code is bringing back the wrong information, is it something glaringly obvious I have over looked?
Your query returns all the status of followers, not the status of followed.
You should change
WHERE followers.beingFollowedUserID='$userid'
to
WHERE followers.followerUserID = '$userid'
In addition, this is unrelated to your question, but your code has a security problem. You should sanitize $userid first before using it in your query.
$userid = (int)$userid
// .. now $userid is safe to use in $sql
The issue was one of the JOINS was looking to the wrong field.
The SQL should of been:
JOIN followers ON userstatusposts.userid = followers.beingFollowedUserID
So the full statement is
SELECT * FROM userstatusposts
JOIN followers ON userstatusposts.userid = followers.beingFollowedUserID
JOIN users ON userstatusposts.userid = users.id
JOIN user_details ON userstatusposts.userid = user_details.userid
WHERE followers.followerUserID = '$userid'
ORDER BY userstatusposts.userstatusid DESC
LIMIT 10
This was solved by a friend of mine not me, but thought I would share the answer for anyone interested.
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
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;