show hyperlink only for a certain user's posts - php

I have a posts table like this:
post_id user_id title date
12 1 abc 7/20/2014
13 1 cde 7/21/2014
14 2 fgh 7/22/2014
And a users table like this:
user_id username email password
1 name1 email1#domain.com ******
2 name2 email2#domain.com ******
The user_id in the posts table is the foreign key of the users table.
Note:
Assume that I store the user's session successfully by using $_SESSION['user_id'] .
Assume that I can echo all 3 post titles along with their usernames successfully too.
Now I would like to echo the edit hyperlink (Edit) for the post titles of a certain user, for example, user_id 1 or 2 after he's logged in. It means that if the user named name1 signs into his account and browses the post whose id is 14, he cannot see the edit hyperlink because it belongs to the another user named name2, whose session id, if any, should be unableable now, and vice versa.
For me, this is my code:
$q = "SELECT title, post_id, p.user_id AS currentuser
FROM posts AS p
INNER JOIN users AS u USING (user_id)
ORDER BY date ASC
";
$r = mysqli_query ($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$uid = isset($_SESSION['user_id']);// variable for the seesion
$current_user = $row['currentuser'];// variable for the certain user ID
if($uid && $uid == $current_user){
echo " Edit </div>";
}
Then I test it, you know, it shows the edit hyperlink in every post title, but not what i expected.
Can you help? Thanks

$uid = isset($_SESSION['user_id']);
This results to either true or false. try
$uid = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : -1;
What I did was use a ternary operator so if the session variable is set, you set it to it otherwise you set it to -1, which most probably does not exsist in a table id column

Related

SELECT one data only if all other table datas arre correct

I've been working on this code for a wordpress social media site where you can visualize people of your opposite sex only if they are not your friends (if they are your friends they'll go to another page)
In the php I already can divide men from women, but now I want to also eliminate the men/women whom already are your friend
$query = "SELECT user_id FROM {$wpdb->prefix}bp_xprofile_data, WHERE field_id = 3 AND value = 'homme'";
(with this I would get only men), now the info about their friend status is in another table, I tried using WHERE EXIST to comprobe it
$query = "SELECT user_id FROM {$wpdb->prefix}bp_xprofile_data, WHERE field_id = 3 AND value = 'homme' AND EXIST (SELECT id {$wpdb->prefix}bp_friends WHERE (initiator_user_id = $user_id AND is_confirmed = 1) OR (friend_user_id = $user_id AND is_confirmed = 1)) ";
But doesn't seems to work.
I just want the user_id from the first table, but if I wanted to extract the friend status (that I dont want to extract, I just want it to corroborate my other info to cut out user_ids) I could apply this query
$already_friends = "SELECT is_confirmed FROM {$wpdb->prefix}bp_friends, WHERE initiator_user_id = $user_id OR friend_user_id = $user_id";
I don't know what is the structure of the tables you are referring to. Based on provided information this might work:
SELECT user_id
FROM {$wpdb->prefix}bp_xprofile_data
WHERE
field_id = 3 AND
value = 'homme' AND
user_id NOT IN (SELECT friend_user_id
FROM {$wpdb->prefix}bp_friends
WHERE initiator_user_id=$user_id AND is_confirmed=1) AND
user_id NOT IN (SELECT initiator_user_id
FROM {$wpdb->prefix}bp_friends
WHERE friend_user_id=$user_id AND is_confirmed=1)
I should acknowledge that this SQL statement looks poor: it is slow and it is hard to read. It should be improved if possible.

Seeing how many posts have been made from male users (Using data from two tables to calculate number)

I have two tables:
users - Where gender information is stored:
id
username
gender
user_thoughts- Where all posts are stored:
id
added_by
What I am trying to do is determine how many posts have been made by male and female users separately. But I am just completely stumped on how to achieve this. So far, I have the following:
<?php
include ("connect.php");
// updating table posts_by_gender whenever admin logs in.
// 1.Get gender of user to compare against the author or the thought
$get_all_users_gen = mysqli_query ($connect, "SELECT gender FROM users WHERE account_type = 'user'");
while ($getting_gen = mysqli_fetch_assoc ($get_all_users_gen)){
$gender = $getting_gen['gender'];
// 2. Get all posts
$getting_thoughts = mysqli_query ($connect, "SELECT username FROM user_thoughts");
$getting_th = mysqli_fetch_assoc ($getting_thoughts);
$added_by = $getting_th['added_by'];
} // while closed
?>
I am just completely confused on what to write after this.
Summary:
Trying to check each row in user_thoughts table, get the added_by data (which is the same as username from users table) and see if that user is male or female.
At the end of the check, I need a variable which holds a number of how many posts belong to male users, and how many to female.
You can do this with a Join... An example given below
SELECT * FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
This will get all user thoughts by male... Then you can do a mysqli_num_rows($query) to get the count.
You can do the same for females...
However, if you only need the count, it may be adviseable to run
SELECT COUNT(*) AS number FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
and this would return the number of rows directly.

If statement not being executed when it is expected to work

I have the following three tables - users_thoughts, users and post_favourites. I have a feature in my social networking site which allows users to favourite a post (posts are stored in user_thoughts and when a post is favourited i.e. when favourite_post.php is called, it will store the favourites in post_favourites table).
If the logged in user has NOT favourited a post, it will show the Glyphicon heart-empty. But if the user HAS favourited a post, it will show Glyphicon-heart.
Lets assume I have the following rows in my tables:
users table:
id: 1
first_name: conor
id: 2
first_name: Alice
id: 3
first_name: Anderson
user_thoughts table:
id: 100
message: This is a post by Alice.
added_by: Alice
id: 101
message: This is a post by Anderson
added_by: Anderson
post_favourites table:
id: 1
user_id: 1 (This is the id of the user who has favourited the post, see users table)
thought_id: 101
Assume I am logged in as Conor. As you can see Conor has favourited Anderson's post, so Glyphicon-heart should appear, as logged in user has already favourited Anderson's post. But Glyphicon-heart-empty is appearing, even though my database says conor has favourited anderson's post.
Here are my queries:
Note: $username is the session variable created for the logged in user.
$count = mysqli_query ($connect, "SELECT * FROM user_thoughts");
while ($row = mysqli_fetch_assoc($get_thoughts_from_db)) {
$thought_id = $row['id'];
}
// Get all user_ids attachted to a thought ($thought_id)
$get_user_id = mysqli_query ($connect, "SELECT * FROM post_favourites WHERE thought_id = '$thought_id'");
$id_fetch = mysqli_fetch_assoc ($get_user_id);
$all_user_id = $id_fetch ['user_id'];
$post_id = $id_fetch ['thought_id'];
// get id of users from users table
$get__id = mysqli_query ($connect, "SELECT id FROM users WHERE username = '$username'");
$id_fetch2 = mysqli_fetch_assoc ($get__id);
$logged_in_user = $id_fetch2 ['id'];
if ($post_id == $thought_id){
// If the post has already been favourited by the username, then display this icon with funtionality.
if ($all_user_id == $logged_in_user){
echo "$get_num_of_favs
<a href='/inc/unfavourite_post.php?id=";?><?php echo $thought_id;?><?php echo "'>
<span class='glyphicon glyphicon-heart' aria-hidden='true' style='padding-right: 5px;'></span>
</a>";
}
// if the post hasn't been favourited by the username, display this icon.
else {
echo "$get_num_of_favs
<a href='/inc/favourite_post.php?id=";?><?php echo $thought_id;?><?php echo "'>
<span class='glyphicon glyphicon-heart-empty' aria-hidden='true' style='padding-right: 5px;'></span>
</a>";
}
}
I need it so already favourited posts by the user who is logged in are dislayed with heart icon i.e. the if statement is executed. But at the moment, Anderson's post of This is a post by Anderson- which is favourited by Conor, is showing with heart-empty - meaning the else statement is being executed and I don't know why?
I can't be sure without your data, but I would put my money on it being that more than one user has favorited this post. Then, the first result returned by
$get_user_id = mysqli_query ($connect, "SELECT * FROM post_favourites WHERE thought_id = '$thought_id'");
will not have the user_id of the current logged in user. You should add the $logged_in_user to the WHERE clause:
$get_user_id = mysqli_query ($connect, "SELECT * FROM post_favourites WHERE thought_id = '$thought_id' AND user_id = '$logged_in_user'");
(Don't forget to escape any data before querying! )
The whole complex logic in php can be substituted by using joins in the sql query to combine data from all relevant tables:
select *
from user_thoughts u
left join post_favourites p on u.id=p.thought_id and u.user_id=$_SESSION['userid']
$_SESSION['userid'] is the user id of the currently logged on user. Store it in session along with the user name.
When you loop through the resultset in php, if thought_id=='' (empty string), then you know that the current user did not like this post yet.

Mysql friends online display

OK,so I have headech from searching everywhere how to solve this problem..Im trying to show online users,but not all users,only who is in your friend list..
So I have table named users_online and when user logs-in in my website in that table is automaticly created 1 row with date,ip,name,user_id and friend_array (where all user's friends are kept)
So for example I log in in my website and row is created in users_online table. I want to see only my friends online and these friends are stored in friend_array column (1,5,16,5 (thats friends id number)).. How can I take data from friends_array colum and see which one of these id's are logged at the moment,which means which of these id's are existing in user_online table and display on my profile?
I hope is not confusing question...
Well thats my code..all stores in online.php file:
// Checking wheter the visitor is already marked as being online:
$inDB = mysql_query("SELECT user_id FROM users_online WHERE user_id=".$userid);
if(!mysql_num_rows($inDB))
{
// Selects some data required to insert into users_online table from users table
$DB = mysql_query("SELECT img,fname,friend_array FROM users WHERE user_id=".$userid);
while($row=mysql_fetch_assoc($DB))
{
$img = $row['img'];
$fname = $row['fname'];
$farray = $row['friend_array'];
}
mysql_query(" INSERT INTO users_online (user_id,ip,img,fname,friend_array)
VALUES(".$userid.",'".$intIp."','".$img."','".$fname."','".$farray."')");
}
else
{
// If the visitor is already online, just update the dt value of the row:
mysql_query("UPDATE users_online SET dt=NOW() WHERE user_id=".$userid);
}
// Counting all the online visitors:
// Thats where i need to work out with friend array..
// I need to display all online friends only
list($totalOnline) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM users_online"));
// Outputting the number as plain text:
echo $totalOnline;
<?php
$friends = array(1,5,16); // Array of friends
$friendIDs = implode(',', $friends); // Turns array into string for SQL select statement
// Gets only friends info from DB
$sql = "
SELECT date, ip, name, user_id
FROM users_online
WHERE user_id IN (".$friendIDs.")";
?>
Sorted out guys! Thanks for your help!
//Selecting an array from db
$DB = mysql_query("SELECT friend_array FROM users_online WHERE user_id=".$userid);
while($row=mysql_fetch_assoc($DB))
{
$friend_array = $row['friend_array'];
$friends = array($friend_array); // Array of friends
$friendIDs = implode(',', $friends);
}
// Counting all the online friends:
list($totalOnline) = mysql_fetch_array(mysql_query("
SELECT COUNT(*)
FROM users_online
WHERE user_id IN (".$friendIDs.")"));
// Outputting the number as plain text:
echo $totalOnline;
Output was 1 user online as i was loged in with 2 browsers and in users_online table was created 2 rows with id 1 and 2..And id 1 had 3 friends in array (2,5,16), and user with id 2 had (1,3)..So in each of the browsers output was 1..Uray! I hope this question helps someone..Btw Im using update function on msql table and if user logs out,i just delete row in users_online table :)
You should consider changing the database schema. Here's an example:
USER table:
id | name | current_session_id
USER_FRIEND_USER table (contains friends that user has added):
user_id | friend_user_id
SESSION table:
id | user_id | created_at | expires_at
SQL Query to get list of friends for user with id '?':
SELECT u.id, u.name FROM USER u
INNER JOIN USER_FRIEND_USER ufu ON (ufu.friend_user_id = u.id)
INNER JOIN SESSION s ON (s.id = u.current_session_id)
WHERE ufu.user_id = ? AND s.expires_at >= NOW();
Here's SQL Fiddle link: http://sqlfiddle.com/#!2/34f83/1/0

database trouble - same values in different rows

I am trying to make my voting system work. I have 3 databse tables:
users, posts, votes
the table users has field username as the primary key. table post has post_id as the primary key. (there are more fields but they don't affect the question/problem)
In the votes table I have 3 fields: username, post_id, vote. vote is enum ('positive', 'negative'). What I'm trying to achieve is that if a user votes for a specific post that is displayed on a page, the query: INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive'); will be executed.
It works if lets say user 123123 has not voted for any post at all yet. When this user votes lets say for post 1, this query works fine. But then if this user wants to vote for a different post, (his vote gets counted - I just copied the part of the code that doesn't work, the rest of it is fine and working) the insert query get's not executed. If user abcd wants to vote for a specific post, this works fine again, but only once. It seems to me that there is some kind of problem with the database, so that there can be only one entry with the same username or post_id. How can I fix this if I want one user to be able to vote for multiple posts? Is there a better strategy for this?
if($runloggedin->num_rows == 1)
{
// If there was no vote for the current posting, then execute this query
$query = "SELECT * FROM posts WHERE post_id='".$post_id."' AND user_name='".$user_name."'"; //get username and the post id
$result = $mysqli->query($query);
$query1 = "SELECT * FROM votes WHERE post_id='".$post_id."' AND username='".$user_name."'"; //check if there is a vote for this post already
$result1 = $mysqli->query($query1);
if ($result->num_rows == 1 && $result1->num_rows == 0)
{
$vote = "INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive')"; // this isn't working. everything else seems to be working (still test it more)
$savevote = $mysqli->query($vote);
$addvote = "UPDATE posts SET posvotes=posvotes+1 WHERE post_id='".$post_id."'";
$runvote = $mysqli->query($addvote);
echo "Thank you for your vote";
}
}
Without seeing how your votes table was created, my guess is that username has been set up as the primary key. This will make the first INSERT work, but all future ones fail. What you need to do is change it to have username & post_id be the primary key
ALTER TABLE `votes` DROP PRIMARY KEY , ADD PRIMARY KEY ( `username`, `post_id` )

Categories