How to recall items from favourites table - php

I have a table of favourites with 'id' 'userid' and 'postid'. I'm trying to select all the entries in 'postid' when 'userid' = 1 for example.
I also have a table of posts with 'id' and others of content. I then want to select all the rows where a 'postid'='id' and then echo the content of those rows.
Essentially filtering the posts by which have been favourited by the user.
What I've got is
<?php
include 'connect.php';
$user = $_SESSION['id'];
$getfaves = mysql_query("SELECT postid FROM Favourites where userid='$user'") or die(mysql_query());
if ($rowfave = mysql_fetch_assoc($getfaves))
{
$faveposts = $rowfave['id'];
$getposts = mysql_query("SELECT * FROM Posts where id='$faveposts' ORDER BY id DESC");
while ($row = mysql_fetch_assoc($getposts))
{
$content = 'content';
echo ($content);
}
}
?>
(the $content = 'content'; is just an example, it's not what I'm actually using in my code)
Obviously this is incorrect, probably because I want to select a list of ids and then search for everything in that list, but I've only coded to look for one item. However I don't know how to correct this.
Thanks in advance for any assistance.

there is a more simple way to do that using just one sql query with the help of INNER JOIN.
so your query will be
SELECT POST.*
FROM `Favourites`
INNER JOIN `Post`
ON Post.id = Favourites.postid WHERE (Favourites.userid='$user')
ORDER BY Post.id DESC;
here is doc about INNER JOIN and its utilities
Please let me know if you need more help,
the php part:
<?php
include 'connect.php';
$user = $_SESSION['id'];
$sql="SELECT POST.*
FROM `Favourites`
INNER JOIN `Post`
ON Post.id = Favourites.postid WHERE (Favourites.userid='$user')
ORDER BY Post.id DESC";
$conn = new mysqli($servername, $username, $password,$dataBase);
$Result = $conn->query($sql);
while($row = $Result->fetch_assoc()) {
//do what you want with the $row, it contain ur resault
}
?>
feel free to test it and report the problem if there is one

Related

Do I need a left, natural or simple join in SQL?

I am new to PHP coding and just trying to fix some functionality on my site that was left over from the lead developer.
The site, [Vloggi], is a marketplace. So I need to show the name of the job poster in the assignments page . The table I have the jobs in only has the ID, not the name.
So I need a join, but I've tried and it breaks the entire site.
The SQL has 17 tables, I need to display the User Name (usr_name) contained in table 3, the organisation contained in table 7 (usrg_orgname) with the job posting user (vlop_usr_id) details in table 14.
The primary key is users.usr_id, which is linked to users_gor.usrg_usr_id and vlog-ops.vlog_usr_id.
Table 3: users
usr_id, usr_email, usr_password, usr_fbuser, usr_fbtoken, usr_name, usr_loc_name, usr_loc_lat1, usr_loc_lon1, usr_loc_lat2, usr_loc_lon2, usr_status, usr_gor, usr_vgr, usr_token, usr_regtoken,
table 7: users_gor
usrg_usr_id, usrg_creditops, usrg_creditvlog, usrg_creditvlogette, usrg_destination, usrg_orgname, usrg_orgtype, usrg_location, usrg_website, usrg_jobtitle, usrg_phone, usrg_address1, usrg_address2, usrg_state, usrg_postcode, usrg_country
Table 14: vlog-ops
vlop_id, vlop_title, vlop_description, vlop_tags, vlop_deadline, vlop_quantity, vlop_quantityposted, vlop_vser_id, vlop_usr_id,vlop_loc_name, vlop_loc_lat1, vlop_loc_lon1, vlop_loc_lat2, vlop_loc_lon2, vlop_campaign, vlop_rules, vlop_tips, vlop_status
So in main.php i have written the following Sql lookup
in main.php, I have the following SQL lookups:
$sql = "SELECT * FROM users_gor WHERE usrg_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_gor = $rows[0];
$sql = "SELECT * FROM users_vgr WHERE usrv_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_vgr = $rows[0];
$sql = "SELECT * FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT * FROM vlog-ops WHERE vlop_usr_id ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT usr_name AS vlop_usr_name FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
And then in the page template itself, I have written
<?php echo $vlop['vlop_vser_id'] ?>
<?php echo $vlop['vlop_usr_name'] ?>
The first one works, the second doesn’t. What I want eventually is to display the user name and the organisation name in a table.
Whenever I try a JOIN or a NATURAL JOIN or a LEFT JOIN it breaks and the entire site goes blank.
Any help for a newbie would be appreciated with a million thanks.
When you use JOIN you need to specify how you're joining them.
In the query below I'm assuming you're looking for the fields in bold from your question.
$query='SELECT u.usr_name, g.usrg_orgname, v.vlop_usr_id FROM users u
JOIN vlog-ops v on u.usr_id = v.vlop_usr_id
JOIN users_gor g on u.usr_id = g.usrg_usr_id';
I believe I got the name of the fields right but if not just replace them with the correct ones.
Once you have the data fetched, you just loop through the results:
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
echo 'User name = ' . $row['u.usr_name'];
echo 'Org name = ' . $row['g.usrg_orgname'];
echo 'Job posting user id = ' . $row['v.vlop_usr_id'];
}

Displaying name from an inner joined table?

I've got two tables, one called category, which has the rows id and name, and another called placecategory, which has the tables id, place_id and category_id. I need to inner join these two to echo out the names of the categories where the placecategory.place_id is equal to a $GET[ID].
I've got this so far, but it echo's out nothing.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name FROM category
INNER JOIN placecategory
ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id.'';
$result = mysqli_query($dbc,$qry);
while ($row = mysqli_fetch_array($result))
{
echo ''.$row['name'].'';
};
?>
This wont fix your query, but it will display the error generated by the incorrect query. Its a start.
I cannot solve the query issue without a better understanding of your schema.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name
FROM category
INNER JOIN placecategory ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id;
$result = mysqli_query($dbc,$qry);
// test the status before continuing
if ( ! $result ) {
echo mysqli_error($dbc);
exit;
}
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
?>

Replaceing mysqli query in while loop with one query using JOIN

I often read that mysql(i) queries used in while loops are not really performance friendly and I'm going to rewrite my code because I think it get better. But here's my question if a JOIN can work here. It's a single post viewing function but you should see every comment which got posted below. I got the comment loop in the loop which the post is printed.
<?php
$result = (empty($_GET['hash'])) ? $_GET['hash'] = '' : mysqli_query($conn, "SELECT * FROM `userposts` WHERE `hash`='".$_GET['hash']."' LIMIT 1");
while($rows = mysqli_fetch_array($result)){
//Output of single post
$commentresult = mysqli_query($conn, "SELECT * FROM `comments` WHERE `postid`='".$rows['id']."'");
while($commentrows = mysqli_fetch_array($commentresult)){
//Output of all comments
}
}
So I think it gets better but the query with JOIN should be like:
$result = (empty($_GET['hash'])) ? $_GET['hash'] = '' : mysqli_query($conn, "SELECT * FROM `userposts` JOIN comments ON userposts.id = comments.postid WHERE `hash`='".$_GET['hash']."' LIMIT 1");
But if I'm trying to post the data of the comments in the while loop which is the singlepost printed it just prints one comment. So what can I do?
regards
Your code is a bit of a mess. You are sometimes call mysql_fetch_results with a string, which is weird.
What you want is this:
"SELECT * FROM comments LEFT JOIN userposts ON comments.PostID = userposts.ID WHERE userposts.Hash = '$_GET['hash']'"
EDIT: sorry, you want LEFT JOIN with comments on the left. Gives you all the comments
EDIT 2: I set this up and it worked as I expected, even with multiple posts with the same hash.
<?php
$hash = $_GET['hash'];
$result = mysqli_query($conn, "SELECT * FROM comments LEFT JOIN userposts ON comments.PostID = userposts.ID WHERE userposts.Hash = '$hash'");
if ( $row = mysql_fetch_array($result)) {
// output of post.
// output first comment
}
while($row = mysqli_fetch_array($result)){
//Output other comments
}
?>

Running if statement based on the results of multiple selections

this is probably going to require something very basic but I can't find an answer to do this in the way I want it to work. What I have is a mysql table of articles and a table of favourites where if you like an article the information is logged. So I need to select all of the articles that I like from one table and then all of the articles from another and display them all as a feed, which I have done. The part I need help with is saying, if I like one of the posts, do not display the like button (Alternatively if I haven't yet liked it, show the button). Can anyone please point me in the right direction with this? Here's the code I have but it only shows the last one I Liked:
<?php
$check_like_sql = "SELECT * FROM posts WHERE type = 'Like' && poster = '$yourid'";
$check_like_res = mysqli_query($con, $check_like_sql) or die (mysqli_error());
if(mysqli_affected_rows($con)>0){
while($likes = mysqli_fetch_array($check_like_res)){
$yourlike = $likes['media'];
}
}
?>
<?php
$get_posts_sql = "SELECT posts.*, members.username, members.avatar, fans.connection FROM posts LEFT JOIN members ON members.id = posts.poster LEFT JOIN fans ON fans.fan = '$yourid' WHERE posts.poster = fans.connection ORDER BY date DESC";
$get_posts_res = mysqli_query($con, $get_posts_sql) or die (mysqli_error());
if(mysqli_affected_rows($con)>0){
while($posts = mysqli_fetch_assoc($get_posts_res)){
$postid = $posts['id'];
etc
etc
if($yourlike == $postid){
$likethis = "Unlike . ";
}
else if($posttype == "Like"){
$likethis = "";
}
else{
$likethis = "Like . ";
}
$post .= "";
}
}
?>
You can left outer join from your articles table to your liked_articles table.
select a.*,
case when la.liked_article_id is null then 'Not Liked Yet' else 'Already Liked' as LikedStatus
from articles a
left outer join liked_articles la
on a.id = la.article_id
and #userId = la.user_id;
This may not be syntactically correct for MYSQL but you get the gist.

PHP Query Call Issue

I have two tables in my database:
1) blog_table
2) content
In blog_table I have values called postID that may or may not match up to values called id in the table content. I am wanting to know how I can write a while loop or foreach loop that will cycle through content table and perform one action if the id equals the value of postID in the blog_table and perform a different action if it doesn't.
Right now I can only get id = postID
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogtable))
{
$getblogposts1 = mysql_query("SELECT postID FROM `$blog_table`");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
if( $row1['postID'] == $row['id']) {
echo "do something<br>";
}else{
echo "do something else<br>";
}
} echo "<p></p>";
}
[Edit based on OP's comments and revised question]
$getblogposts = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogposts))
{
$matches = mysql_query("SELECT * FROM $blog_table WHERE postID = $row['id']");
if (mysql_num_rows($matches) > 0)
{
// do something
}
else
{
// do something else
}
}
Regarding a different design, I can't say for sure that it's necessary, but I don't like running a loop of queries like this. I think one query should be enough to get everything you need in this case. Maybe if you describe your application, we could find a better query or more appropriate design.
Just providing an easier to see solution for you to your problem.
I suggest using inner joins which will solve the issue at hand.
For example, Something like:
SELECT * FROM content AS C INNER JOIN $blog_table AS B on B.postID = C.id
Here is a great introduction to joins (inner, left, right, full):
http://www.w3schools.com/sql/sql_join.asp
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT postID FROM `$blog_table`");
while ($row = mysql_fetch_assoc($getblogtable))
{
$postID = $row['postID'];
$getblogposts1 = mysql_query("SELECT * FROM content WHERE id = '$postID' ORDER BY `order` ASC");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
// if( $row1[id] == $postId )
// do something
// else
// do something else
}
}

Categories