MySQL inner join 2 tables to match user number to user name - php

I'm sorry this has probably been answered hundreds of time but I'm totally lost between different scenarios here.
What I want is pretty simple. I have 2 tables "bets" and "users".
In the table "bets", I put the UserID instead of the UserName. In the table "users", the UserName is linked to the UserID.
I would like to be able to read the data from the table "bets" and display the UserName instead of the UserID, so I will need some sort of code to match the UserID contained in the table "bets" and return the UserName instead.
The MySQL query I have for now:
$sql5="SELECT * FROM Bets, Users WHERE GameID = '$NGnumber' ORDER BY DrawOrder";
$result5 = mysql_query($sql5) or die(mysql_error());
while($rows5 = mysql_fetch_assoc($result5)){
...
I can easily echo $rows5['UserID'] but I would like the UserName (in the Users table) instead. How can I do that?
Thanks!

Use inner join:
SELECT * FROM Bets INNER JOIN Users ON Bets.userID = Users.userID WHERE GameID = '$NGnumber' ORDER BY DrawOrder

Replace the query:
SELECT * FROM Bets b INNER JOIN Users u
ON b.GameID = u.GameID
WHERE GameID ='$NGnumber' ORDER BY DrawOrder"

Related

joining 2 tables in msqli

table posts
table users
how would i count posts for specific user logged in. for example when user with id 3 is logged in it should show me 4 posts
I already did it for total posts count:
<?php
$post_query1 = "SELECT count(*) AS total FROM posts ";
$post_result1 = mysqli_query($db, $post_query1);
$post1 = mysqli_fetch_array($post_result1);
?>
Try below example :
select count(*) as total from user as u inner join post as p on p.id_user = u.id_user AND u.id_user = 3
If you want to get only the posts count for the particular user, say user with id = 3, your query should be this:
$query = "SELECT count(*) AS total FROM posts WHERE id_users = 3";
But if you want to get both the posts count as well as the user information and other post information, you will have to run a join query on both the users and posts table. Your query would now become:
$query = "SELECT u.*, p.*, count(p.id_posts) FROM users AS u JOIN posts AS p ON u.id_users = p.id_users WHERE p.id_users = 3";
Some Useful Notes
p.* - * is a wildcard character that means get all the columns in the posts table
u.* - * is a wildcard that means get all the columns in the users table
posts as p - AS is for aliasing. So, we are giving posts table a temporary name.
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
Note: It is necessary that you have to join two/more tables only with the help of foreign key. Without the foreign key is is meaningless to join two or more tables
Reference 1: https://www.w3schools.com/sql/sql_join.asp
Reference 2: https://www.tutorialspoint.com/mysql/mysql-using-joins.htm
As per the Question what you have asked to join the tables
Query:
SELECT * FROM TABLE 1 JOIN TABLE 2 ON TABLE1.id = TABLE2.id WHERE TABLE2.ID=3
Kindly replace TABLE1 & TABLE2 with the Tables that are to be joined and the id with the foreign key what you have specified in the Table.
Hope so this might be helpful for you to write your own code in future. Happy Coding :)
You have only to use a simple join.
SELECT count(*)
FROM USER u,
post p
WHERE p.id_user = u.id_user
AND u.id_user = 3

How to JOIN 2 tables on mySql?

I have two tables: publick_feed and users
I want to SELECT all from public_feed and also SELECT a three columns from users whose id is the same of user_id in public_feed
and assign the rows returned from public_feed to the column in users table ( correspondent)
I try this:
<?php
$sql = "
SELECT * FROM public_feed
WHERE user_id IN
(SELECT id FROM users) AND
(SELECT Firstname,Lastname,Avatar FROM users WHERE id IN(SELECT user_id FROM public_feed))
";
$query = mysqli_query($dbc_conn,$sql);
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
//echo rows with correspondent details from the users table
echo $row['user_id'];
}
}
<?
Please any help will be much appreciated.
Thank you.
Or version with left join in case if there is no user in public_feed, and you still want to fetch user data
SELECT
u.*, f.*
FROM
public_feed f LEFT JOIN
users u ON f.user_id = u.id;
Because author asked for explanation, here it is:
First we are going to use table name alias to make query shorter
public_feed f
and
users u
we are saying that want to refer to tables with an alias. Of course * means that we want to select all columns
SELECT users.*, public_feed.*
is equal to
SELECT u.*, f.*
Of course you can use any other letters as an alias
Next we are saying that public_feed.user_id must be equal to users.id. But when public feed entry does not exists just display columns with null values. This is why we are using LEFT JOIN instead of INNER JOIN. In general JOINS are used to fetch related data from more than one related tables.
ON keyword is saying values from which columns in the tables must be equal to satisfy the request
I think doing a join would be cleaner than using a complicated subquery:
SELECT u.Firstname,
u.Lastname,
u.Avatar,
COALESCE(pf.User_id, 'NA'),
COALESCE(pf.Post, 'NA'),
COALESCE(pf.Date, 'NA')
FROM users u
LEFT JOIN public_feed pf
ON u.Id = pf.User_id
I chose a LEFT JOIN of users against public_feed on the assumption that every feed will have an entry in the users table, but not necessarily vice-versa. For those users who have no feed entries, NA would appear in those columns and that user would appear in only a single record.

Mysql inner join/ multiple selects in one query?

Hi all!
I'm scripting a guestbook (personalized for each user). I have one table for users and a different one for the guestbook. Now, the way I'm currently displaying the name of the author of a post is not optimal. I simply have a row in the DB for "fromname" i.e the authors name.
I would like to select the authors name based on the authors ID and matching that to their name in the "users" table.
So... This is my mysql query right now:
$sql = " SELECT
pid,toid,fromid,message,fromname,name,pdate,flag
FROM gbook INNER JOIN users
ON id='{$_GET['id']}'
WHERE toid='{$_GET['id']}'
ORDER BY pdate DESC";
I guess I need to like... Select the name on a different condition but in the same query. But I don't know how.
I hope you understand my problem.
Help will be greatly appreciated!
/Jafool
Assuming your users table has a column called username, the following should do what you want:
SELECT
pid,
toid,
fromid,
message,
u.username,
name,
pdate,
flag
FROM gbook INNER JOIN users u
ON id='{$_GET['id']}'
WHERE toid='{$_GET['id']}'
ORDER BY pdate DESC"
All I did was alias the user table (as u), and refered to u.username instead of the fromname you had before.
From what I am seeing it looks like you need to link to the users table twice since you have a fromid and a toid. If you have a users table, why would you have a fromname field in the gbook table? Anyway if my assumption is correct then you may be interested in the following query:
SELECT g.*, u1.username AS ToUser, u2.username AS FromUser
FROM gbook AS g
INNER JOIN users AS u1 ON u1.id = g.toid
INNER JOIN users AS u2 ON u2.id = g.fromid
WHERE g.toid = '{$_GET['id']}'
ORDER BY g.pdate DESC
Hard coding the name in the guestbook table is indeed dirty. Assuming your table structure is something like this:
users( id, name )
gbook( pid, toid, fromid, message, fromname, name, pdate, flag )
your query is already almost ok. Just change it as follows to select all columns of both tables:
$sql = " SELECT *
FROM gbook g INNER JOIN users u
ON u.id=g.fromid
WHERE toid='{$_GET['id']}'
ORDER BY pdate DESC";
Then you can display the name with something like
$result = mysql_query($sql);
while( $val = mysql_fetch_array($result) )
{
$username = $val["u.name"];
}

MYSQL combine two queries to get the functionality

I have a query that retrieves the users that are online, and a users friends. Now I want to know the best way to combine the two so I can get the results of the users friends that are online.
Friends query:
SELECT
CASE WHEN userID=$session
THEN userID2
ELSE userID
END AS friendID
FROM friends
WHERE userID=$id OR userID2=$session
LIMIT 18
users online:
SELECT *
FROM usersActivity
WHERE setActivity!=3
AND userID!=$session
usersActivity.userID needs to match friendID
Query should be:
SELECT users.name
FROM usersActivity
INNER JOIN friends ON
(usersActivity.userID = usersActivity.userID AND usersActivity.userID2 = $session) OR
(usersActivity.userID2 = usersActivity.userID AND usersActivity.userID = $session)
INNER JOIN users ON
(usersActivity.userID = users.userID) OR
(usersActivity.userID2 = users.userID)
WHERE usersActivity.setActivity!=3
AND usersActivity.userID!=$session
AND users.userID != $session
GROUP BY users.id
You may use COUNT(user.id) if you want only count of users. Or select all names (store them for later use in listing) and use only mysql_num_rows() for getting actual number of friends online
I think I understand what your after:
SELECT userID FROM usersActivity
WHERE setActivity !=3
AND userID IN(
(SELECT userID FROM friends WHERE userID2=$id)
);
This assumes you have double rows for your friend linking table and $id is the current logged in user.
userID userID2
1 2
2 1
Using subqueries in your where statement should consolidate this. Not sure if this will be faster or not, depends on how you are doing things so profile it. You can join on your users table to get the friends name information and what other info you need.

MySQL SELECT * FROM tbl1 WHERE smth AND a field from another table is something

I have two tables. One contains information on hotels, added to my website by users. It contains a field called Username that contains the username of the person that has uploaded it. The second table contains user info (including a field called "active" which indicates if a user has paid or not). I need to get entries from the first table ONLY for users that have paid. Currently I'm doing it like this in PHP:
$hotelsq = mysql_query("SELECT * FROM trips_all ORDER BY id DESC ");
while ($hotel = mysql_fetch_array($hotelsq)) {
$username = $hotel['username'];
$isactiq = mysql_query("SELECT * FROM users WHERE username='$username'");
$isact = mysql_fetch_array($isactiq);
if ($isact['active'] == 'member') {
What I need is a single query that will select all of the hotels in the first table, then check if the user ("username" column) it has been uploaded from has "member" in the "active" column. The username column in the second table is named "username" as well.
What would that query look like ?
select t.*
from trips_all t
inner join users on t.username = u.username
where u.active = 'member'
Check INNER JOIN:
SQL INNER JOIN Keyword
So something along the lines of:
mysql_query("SELECT * FROM trips_all INNER JOIN users ON trips_all.username=users.username WHERE users.active='member');
select * from trips_all t
left join users u on t.id= u.userid
where u.active = 'member'

Categories