If statement not being executed when it is expected to work - php

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.

Related

show hyperlink only for a certain user's posts

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

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

Selecting user specific records for logged in user using multiple tables PHP MYSQL

I have 2 tables one called users and one called tv shows. Im storing the name of the user in a variable called username by doing. The users table holds the user_id PK, username, password and the tv shws table stores the tv_id PK, user_id FK, TV Show Name
$username=$_SESSION['username'];
i want to be able to display all the tv shows for the specific user that has logged in and im guessing i would need to show all the results for the user id assigned to the user that has logged in because the user_id in the tv shows table is a foreign key of the primary key user id in the users table.
Code:
$user = "SELECT user_id FROM users where username='$username'";
if(!$rs = mysql_query("SELECT * FROM tv shows WHERE user_id='$user'")) {
When i run this code i get "cannot select table"
Try this
$query = 'SELECT * FROM tv_shows where user_id=(SELECT user_id FROM users where username="'.$username.'")';
okay ,try this:
<?php
$user = musql_query("SELECT * FROM users where username='$username'");
$result = mysql_fetch_array($user);
$userid = $result['user_id'];
$sql = "SELECT * FROM tv shows WHERE user_id=".$userid;
$get_tv = mysql_query($sql);
$make_array = mysql_fetch_assoc($get_tv);
print_r($make_array);
?>
Happy coding!!
First of all, as a better design, you can have user_id in your $_SESSION.. so that you can avoid unnecessary query...
Here the problem could be due to Single quote ... So please escape your Single quote ..
Thanks
SELECT username,user_id
FROM users as a
JOIN tv shows as b ON b.user_id_id=a.user_id
WHERE a.username='{$username}'
managed to figure it out myself with help from Tornado
if(!$rs = mysql_query("$query2")) {
$query2 = 'SELECT * FROM tv_shows where user_id=(SELECT user_id FROM users where username="'.$username.'")';

Joining tables in MySql with one common field but different values for the common field

how to join 3 tables with one common field like
table1:c_id,username,password,c_role
table2:p_id,username,password,c_role
table3:s_id,username,password,c_role
in this c_role field is common
here i assigned
enum '1' for c_role in table1
enum '2' for c_role in table2
enum '3' for c_role in table3
for giving rights to 3 different users like corres, principal and for a staff when they login..
Now when they login it should identify the user and take them to their page..
You should have one table that contains the following columns:
id (unique, primary), username, password, role (INT, would be assigned 1-3 for principal, staff or corre depending on the user)
Additionally
You could have another table called roles if you want set up like this:
id (unique, primary), title (options for title would be principal, staff, or corres)
When the user logs in just do something like
if($role == 1){
// redirect to principal page
}
elseif($role == 2){
// redirect to staff page
}
elseif($role == 3){
// redirect to corres page
}
I'm not certain but I believe this would work as well. Try this query.
(SELECT '1' AS role FROM table1 WHERE username = $username AND password = $password)
UNION ALL
(SELECT '2' AS role FROM table2 WHERE username = $username AND password = $password)
UNION ALL
(SELECT '3' AS role FROM table3 WHERE username = $username AND password = $password)
Assuming the user is only located in ONE of those three tables then it should match the username and password and find out which table the user is coming from. Then you can pull out the role by using
$role = $row['role'];
If the username/password combination is incorrect then $role would be empty or you could fetch the number of rows [using $iscorrectuser = mysql_num_rows($query)] where there is a match and the number of rows would be 0. You could then redirect the user trying to log in with a "Unsuccessful login" error message.
The only joins would be on username (and password ?) unless c_id, p_id and s_id are all the same id?
You can't join on role seeing as they are different in each table, aside from an utterly daft role = 1 in Table1 is the equivalent of role = 2 in table2.
Do you mean a union? As in you want
User Password Role
Fred Fr3d 1
Fred ??? 2
Fred ??? 3
Not sure what you are trying to achieve with this schema, but it breaks near every rule in the book, and doesn't seem to meet your needs....
Based on your comment, one way you might look at is.
Is
Users (UserID, UserName, Password etc) Key UserID
Roles (RoleID, RoleName etc) Key RoleID
UserRoles(UserID,RoleID) Key UserID,RoleID
You need to learn a bit about databases particularly normalisation, first three forms should do for most things.
Then
Select UserName, Password,RoleName From Users
inner join UserRoles on Users.UserID = UserRoles.UserID
inner join Roles on UserRoles.RoleID = Roles.RoleId
and such like become possible and efficient.
session and include functions are given:
session_start();
include("config.php");
if(isset($_POST['T_UserName']) && isset($_POST['T_Password']) && !empty($_POST['T_UserName']) && !empty($_POST['T_Password']))
{
username and password sent from form:
$T_UserName=$_POST['T_UserName'];
$T_Password=$_POST['T_Password'];
To protect MySQL injection:
$T_UserName = stripslashes($T_UserName);
$T_Password = stripslashes($T_Password);
$T_UserName= mysql_real_escape_string($T_UserName);
$T_Password = mysql_real_escape_string($T_Password);
$sql="SELECT * FROM login WHERE username='$T_UserName' and password='$T_Password'"; $result=mysql_query($sql);
Mysql_num_row is counting table row:
$count=mysql_num_rows($result);
If result matched $T_UserName and $T_Password, table row must be 1 row :
if($count==1)
{
Register $T_UserName, $T_Password and redirect to file "correspindex.php" :
session_register("T_UserName");
session_register("T_Password");
redirect to error page or display error message then :
if(isset($_POST['emp_role'])
{
$userinfo = mysql_fetch_assoc($sql);
$emp_role = $userinfo['emp_role'];
if($emp_role == 1)
{
header("location:corrrespondindex.php");
}
elseif($emp_role == 2 )
{
header("location:principalindex.php");
}
elseif($emp_role == 3)
{
header("location:staffindex.php");
}
closes out if the user DOES exist:
header("location:loginhome.php");
}
else
{
echo "Wrong Username or Password";
}
}
}
php is closed
this is the php code im getting so many error
i create 1table with id,username,password and role(ENUM,values as'1','2','3' –
any else shud i do in the code???

how to print out a username and user age based on session login

i am fairly new to php. I am trying to print out the username and age based on the user session login, and cant seem to figure it out.
I have two separate table, one for login and another that contains the users info.
user table id-> 1 | logon -> shawn#aol.com | passwrd -> somthing
usersinfo id-> 1 | logon ->shawn#aol.com | username -> mathewkng1 | age -> 23
i can print out the session login using $_SESSION['logon'], this will give shawn#aol.com
what i want to do is instead of printing out shawn#aol.com i want to print out mathewkng1, age 23.
i tried,
SELECT users.*, usersinfo.* FROM users, userinfo WHERE users.logon = userinfo.logon
$logon = session_start();
if($_SESSION['logon']){
while($rows = mysql_fetch_array($user )){
$username = $rows['username '];
$age= $rows['age'];
}
echo " .$username." <br> ".$age." ";
}
i get the following error $username and $age not defined.
First advice is not to relay on the logon as a key for the second table. Rather use a field id_user instead of logon an id in the userinfo table.
then you can change also the select to
Select * from users join userinfo on users.id = userinfo.id_users
then you have an typo in
$username = $rows['username '];
i don't see where you do $_SESSION['logon'] and what you add there but i guess that it is an ID of that users table, so you should add that to the select up there.
$username = $rows['username '];
There is a space within the string behind username. I guess that shouldn't be there. Also, I cannot see if these tables contain an age. If $username is not defined, it might be because there is no record returned. Assumingly there is an error in your query (could by a Duplicate Fieldname error because both returned tables will contain the same logon field), but there could also be an error in the way you execute the query.
Please try these suggestions and check for the result of mysql_query and mysql_fetch_* to see if an error occurred. If mysql_query returns false (check using the === operator), get the result of mysql_error() to see what the exact error is.
Post that error and a little more code if you need more help.
Looking at your table structure, you don't need the join.
This sould be sufficient:
SELECT * from usersinfo where logon = 'shawn#aol.com'
session_start();
if($_SESSION['logon'])
{
$query = "SELECT * FROM usersinfo WHERE logon=" . $_SESSION['logon']
$res = mysql_query($user, $sqlConnection)
while($row = mysql_fetch_array($res))
{
$username = $row['username'];
$age= $row['age'];
}
echo $username ." <br /> ".$age;
}

Categories