Is there a better way to get info from 2 tables - php

In database the users have a row called weapon_id which determines what weapon he uses from another table with weapons.
Is there a better way to get that info like join table or something?
$user_get = mysqli_query($db, "SELECT * FROM members WHERE id = '".$_SESSION['sess_id']."'");
$user = mysqli_fetch_assoc($user_get);
$weapon_get = mysqli_query($db, "SELECT * FROM weapons WHERE weapon_id = '".$user['weapon_id']."'");
$weapon = mysqli_fetch_assoc($weapon_get);

use a join like this
$user_get = mysqli_query($db, "SELECT * FROM members m LEFT JOIN weapons w ON(w.weapon_id=m.weapon_id) WHERE m.id = '".$_SESSION['sess_id']."'");
$user = mysqli_fetch_assoc($user_get);
change the join type as per your requirement. the above query for only example
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
more about join click here
AND also check this http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

SELECT * FROM `weapon` as w
JOIN `user` as u
on w.weapon_id = u.weapon_id
and u.id = :session_id
How about this ?

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

Selecting from comments and images table for each article in a while loop

I have an articles table that and I am displaying it in the homepage in a while loop. Inside the while loop I want to display the comments count and images count for each article.
It is working for me now, but it is three queries in total, I am trying to combine it in the first query and then just display all of them in one while loop. Here is what I am trying to achieve:Articles page
The current format I am following:
//a represents articles table, c represents comments table, i represents image table
$query = mysqli_query($conn, "SELECT a.a_id, a.title, a.datetime, a.user_id FROM a ORDER BY a.datetime DESC");
while($fetch = mysqli_fetch_assoc($query){
$imageQ = msqli_query($conn, "SELECT COUNT(image_path), image_path FROM i WHERE a_id = '$fetch['a_id']'");
$imageFetch = mysqli_fetch_assoc($imageQ);
$commentQ = mysqli_query($conn, "SELECT COUNT(comment_id) FROM c WHERE a_id = '$fetch['a_id']'");
$commentFetch = mysqli_fetch_assoc($commentQ);
}
I want to cram all of these queries into one single query that fetches the article and comments count and image count for each article and the first image.
The images and comments are separate dimensions of the data. So, you have to be careful about how to bring them together. In your case, you can aggregate the values before doing the joins:
SELECT a.a_id, a.title, a.datetime, a.user_id,
i.num_images, c.num_comments
FROM a LEFT JOIN
(SELECT a_id, COUNT(image_path) as num_images
FROM i
GROUP BY a_id
) i
ON i.a_id = a.a_id LEFT JOIN
(SELECT a_id, COUNT(comment_id) as num_comments
FROM c
GROUP BY a_id
) c
ON c.a_id = a.a_id
ORDER BY a.datetime DESC;
You can use mysql nested queries something like
SELECT a.,tab1.,tab2.* FROM a INNER JOIN (SELECT * FROM b ) as tab1 INNER JOIN (SELECT * FROM c) as tab2
Hope this can get you to get desired output.
Thanks

Merging two queries with the same binded parameter

I have a first SQL query getting a table with id_member as parameter
$stmt = $mysqli -> prepare("SELECT a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster,
FROM alerte a,
alerte_par_roster ar,
roster_par_membre rm
INNER JOIN roster r
ON r.id_roster = rm.id_roster
WHERE rm.id_roster = ar.id_roster
AND ar.id_alerte = a.id_alerte
AND rm.id_membre = ?");
$stmt->bind_param('i', $id_membre);
I need to insert a second query counting the number of lines in another table.
The second query is:
"SELECT COUNT(DISTINCT id_roster)
FROM disponibilites_par_member_alertes
WHERE id_member = ?
AND id_alerte = ?"
As you can notice id_member is the identical in both queries but id_alerte (used as a parameter of the second query is a result of a first query).
I hope I am clear.
Any idea will be very welcome
I don't fully understand what your queries are intended to do. It would help to have clear information on the table structure and what each of the fields represents. I've tried to make a guess based on the table names but can't be certain it's correct.
The first thing I did was just to transform your WHERE condition such that each of the tables are joined explicitly. This is just for readability.
SELECT
a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster
FROM alerte a
INNER JOIN alerte_par_roster ar
ON ar.id_alerte = a.id_alerte
INNER JOIN roster_par_membre rm
ON rm.id_roster = ar.id_roster
INNER JOIN roster r
ON r.id_roster = rm.id_roster
WHERE
rm.id_membre = ?
Now we combine with the other query:
SELECT
a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster,
rc.id_roster_count
FROM alerte a
INNER JOIN alerte_par_roster ar
ON ar.id_alerte = a.id_alerte
INNER JOIN roster_par_membre rm
ON rm.id_roster = ar.id_roster
INNER JOIN roster r
ON r.id_roster = rm.id_roster
LEFT JOIN (
SELECT id_membre, id_alerte, COUNT(DISTINCT id_roster) AS id_roster_count
FROM disponibilites_par_member_alertes
GROUP BY id_membre, id_alerte
) AS rc
ON rc.id_membre = rm.id_membre
AND rc.id_alerte = ar.id_alerte
WHERE
rm.id_membre = ?
With my own generated data I get results like this:
If this is not enough to solve the problem you will need to provide more details about the tables and the design.

getting data from four tables with tight WHERE clause

i need help getting data from different tables and insert into other different table Here are the Queries
"SELECT commentID, date, comment, subject, parentID, aBUserID FROM comments WHERE status = 'APPROVED'"
"SELECT topicID, subForumID, aBUserID, lastPostID, views, replies, startDate FROM topic WHERE status = 'APPROVED' AND topicID = $parentid";
// $parentID need to be matched from above query parentID,
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID";
// $cmtaBUserID = aBUserID from first query
"SELECT userName FROM users WHERE aBUserID = $topicaBUserID";
//$topicaBUserID = aBUserID from second query
Last 2 queries are from same table but using different where clause
i used different inner join left join from solutions posted here but non of these worked for me stuck since last 2 weeks please help
PS data from all above Queries will be inserted to a single table i need these to be combined so i can have them all in one place
If you want to perform the operation in same query use 'OR'
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID OR aBUserID = $topicaBUserID";
Please try this
SELECT userName from users where aBUserID IN(SELECT aBUserID FROM comments WHERE status = 'APPROVED')
Couldn't test it but Maybe this is what you are looking for.
SELECT c.commentID, c.date, c.comment, c.subject, c.parentID, c.aBUserID,
t.topicID, t.subForumID, t.aBUserID, t.lastPostID, t.views, t.replies, t.startDate,
u.userName
FROM
comments c
left outer join topic t on t.topicID = c.parentID
left outer join users u on u.aBUserID = c.aBUserID and u.aBUserID = t.aBUserID
WHERE
c.status = 'APPROVED' and t.status = 'APPROVED';
try this:
SELECT
comment.[commentID],
comment.[date],
comment.[comment],
comment.[subject],
comment.[parentID],
comment.[aBUserID],
commentuser.[userName],
topic.[topicID],
topic.[subForumID],
topic.[aBUserID],
topic.[lastPostID],
topic.[views],
topic.[replies],
topic.[startDate],
topic.[userName]
FROM comments comment
LEFT OUTER JOIN users commentuser
ON commentuser.aBUserID = comment.[aBUserID]
LEFT OUTER JOIN
(
SELECT
t.[topicID],
t.[subForumID],
t.[aBUserID],
t.[lastPostID],
t.[views],
t.[replies],
t.[startDate],
u2.[userName] --user from users table joined to topics table
FROM topic t
LEFT OUTER JOIN users u
ON u.aBUserID = t.[aBUserID]
WHERE t.[status] = 'APPROVED'
) topic
ON topic.topicID = comment.parentID
WHERE comment.[status] = 'APPROVED'

How to make a fancy mysql join that can join three tables and detect if one table DOESNT have my item

php mysql query
I have multiple linked tables - I also have a table that only creates and entry if certian conditions exist so I would like to add that into my query to avoid having to go through thousands of query searches looking for this special case
here is my current query
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city'";
I then go through each item that was returned (in the thousands)
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$sentdata = getothertable($row['UUID']); //checks if the item is in the table
$sent = $sentdata ['senttoGarcom'];
if($sent == 0) //if it wasn't found add it to my list
{
array_push($Contracts,$row['UUID']);
}
}
instead of all that I would like to just make it one query - pseduo code something like this
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
INNER JOIN contract_sales c ON a.UUID = c.contractUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city' AND c.DOESNOTEXIST";
this way I dont have to return thousands I will only be returned the few that are not yet in the contract_sales table and I can go about my business...
Appreciate any help!
just check for NULL rows of c with a outer join
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
LEFT OUTER JOIN contract_sales c ON a.UUID = c.contractUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city' AND c.contractUUID IS NULL ";
I think this is a left outer join problem
Have a look at this example. You specifically need to have a check for a null in a column in the table which you want to find the missing row rof
mysql left outer join
Sounds like a NOT EXISTS correlated subquery is what you need:
$query = "SELECT a.UUID FROM contract a
INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID
WHERE b.garcom_UUID = '$garbCom'
AND b.city_UUID = '$city'
AND NOT EXISTS (SELECT 1
FROM contract_sales c
WHERE c.contractUUID = a.UUID)";

Categories