Show query result for logged in user - php

I got some great help in my last question, someone directed me to go learn about database tables and stuff, since then I blasted through most of the things I was stuck on!
Unfortunately I've reached another problem which I can't seem to fix.
I can merge two tables and get results, but I can't seem to get the results of the user that is logged in. For example, I display the amount of 'gold' the user has at the top left corner, I have 7 users that have 100 gold assigned to them and I only want them to be seen when the user that the gold belongs to is logged in, if you get me? Here's what it looks like all the time, whether logged in or not: http://imgur.com/kgqgnPc
here's the code
$sql = 'SELECT `stats`.`id`, `stats`.`gold`, `users`.`id` FROM stats, users WHERE username = username';
$con=mysqli_connect("localhost","root","","game");
mysqli_select_db($con,'game');
$retval = mysqli_query($con,$sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC))
{
echo "Gold :{$row['gold']} <br> ".
"--------------------------------<br>";
I'm 90% sure it's to do with the "select/from/where" part but I've done lots of research and can't get it right :(
Database structure: http://imgur.com/DR40iv8 (Sorry, I don't know how to get it without the command line)

I see that you have the gold in one table and the users in another. The gold in the gold table should point to what user owns the gold. Like for example owner_id pointing to the users id. Then you should be able to do like this:
$sql = "SELECT stats.id, stats.gold, users.id, users.username FROM stats, users WHERE users.username = '$username' AND stats.owner_id = users.id";
This tells to find user with the username specified in $username, and the gold with owner_id the same as the users id matching that username.
Hope this helps

Try:
SELECT `stats`.`id`, `stats`.`gold`, `users`.`id` FROM stats, users WHERE stats.username = users.username
Because username is common to both tables (I assume), it's important to explicitly state which table username is coming from.
Edited to add:
You would still need to specify which username you want from the results of the joined tables.
$sql = 'SELECT `stats`.`id`, `stats`.`gold`, `users`.`id` FROM stats, users WHERE `stats`.username = `users`.username AND `users`.`'.$yourUserVariable.'`;

Related

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.

Best way to alert user

I have a database with a table called userbadges . All users have all badges at level 0 "locked" (greyed out) . They can unlock it at level 1 , all the way to level 3. Each level is worth points.
userbadges {user_id,badge_id,level,score,seen}
What would be the best way for me to alert the user that they
a) have unlocked a new badge
b) have leveled up a badge
I have this code , but it doesn't seem right. It counts the number of new badges ():
function countNewBadges() {
require "connect.php";
$newbadges = mysqli_query($connection,"SELECT users.studentid, individualbadges.badgename, ub.level, count(ub.seen) as total FROM userbadges ub
INNER JOIN users ON users.id = ub.user_id
INNER JOIN individualbadges ON individualbadges.id = ub.badge_id
WHERE studentid = '".$_SESSION["studentid"]."' && seen=0 && level!=0") or die(mysqli_error($connection));
while ($data = mysqli_fetch_array($newbadges)) {
echo $data['total'];
}
}
I also have code to set the seen field of the badges table to 1.
I would make a messaging system: Create a table message with text, title. (for every message you have or dynamicly) Then make a table user_has_message where you got the 2 Keys to join, and a boolean if read.
With a simple Select * from user JOIN user_has_message on ... and iduser = ... JOIN message on ... where read = false you get all your alerts/Messages for a specified user.
EDIT: Now you can simply add an entry to user_has_entry, in which you specify which user should get which message.
Now you have much possibilities: add the date with default NOW(), to know when the message occoured, give the user the possibility to delete this message (what only deletes the entry on the user_has_message), add tho option to mark a message as unread, etc etc ...
Shure you can also use those messages for other things like a Welcome-Message etc. Or add a cronjob to send an email to the users with open messages older than 5 days. Or even implement a chat-system...

php - get how many available ads from table

I have this table advertisements, where I store all my advertisements. Everytime a user clicks on an advertisement, I record that click into a table called advertisement_clicks.
What I store in both tables is: userid and a unique token.
So, I want to count how many available advertisements there is for the user to see. Currently, I am doing it like this:
$ex = $dbh->prepare("SELECT * FROM advertisements WHERE status='2' AND fixed='0'");
$ex->execute();
foreach ($ex as $normal) {
$search2=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE token=:token AND username=:username");
$search2->bindParam(":token",$normal['token']);
$search2->bindParam(":username",$userdata['id']);
$search2->execute();
}
$allnormal = $ex->rowCount();
$clickednormal = $search2->rowCount();
$normalads = $allnormal-$clickednormal;
$allnormal = how many advertisements is available.
$clickednormal = how many of these advertisements has the user clicked.
So the above approach is a bit messy and it doesn't give the correct result.
Can someone help me do this a smarter way?
You can use COUNT to get it through SQL instead.
SELECT count(*) as addCount FROM advertisement_clicks WHERE
token=:token AND username=:username"
I havn't messed with php in a while so I'm not going to even attempt to write some code lol, but the way I did it was I executed this query:
SELECT COUNT(*) FROM advertisement_clicks WHERE token=:token AND username=:username
Then get the query result which will return the advertisement count.

MySQL INNER JOIN using an OR whilst logging in

My table structure is as follows:
~ MEMBERS ~
UID (a-i)
NAME
EMAIL
~ COUPLES ~
UID_1
UID_2
PASSWORD
SALT
When a couple sign up, their UIDs get inserted in to the couples table, along with their joint password (and its salt). Now, when logging in, I need to join the tables so I can check the password for either user.
i.e. Find Email Address > See which Couple they are in > Check against Password
This is my current query:
$query = "SELECT * FROM MEMBERS m
INNER JOIN COUPLES c ON ((c.UID_1 = m.UID) OR (c.UID_2 = m.UID))
WHERE EMAIL = '$email'";
(I'm only using * for now as I can't figure out exactly what I need to select for the INNER JOIN to work.)
And the rest of the code on login-script.php is as follows:
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0) {
header('Location: index.php?msg=error4');
exit();
}
$data = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $data['SALT'] . hash('sha256', $password));
if ($hash != $data['PASSWORD']) {
header('Location: index.php?msg=error5');
exit();
}
else {
echo "Logged in.";
}
?>
If I try and log in, the error message ?msg=error5 gets thrown, which means that the passwords do not match, but I cannot see a problem in that part of my code. I believe it's telling me they do not match because it's not looking in the right table/for the right data, which must be something wrong with my INNER JOIN.
Any help would be much appreciated.
EDIT: I realise now that it would have made a lot more sense to have just put the password and salt in to MEMBERS for both records so I'm only selecting from one table, but the deed is done and I'm curious to see if this is possible.
Actually, I tried your structure and code on http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all and this works for me:
SELECT * from members M JOIN couples C ON uid_1=Uid or uid_2=uid
WHERE email='youremail';
Perhaps the problem is that in the table there is more than 1 couple a person is actually in?
Like:
uid_1, uid_2, pass
1 2 xxx
1 3 yyy
You should either limit it on database side to unique columns or change code, because if you don't, you might be getting more than 1 row as result and you would need to check every couple's password against particular UID.

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.'")';

Categories