Queries from Diffrent Tables How to Join Suggest PLease (PHP)(SQL) - php

I need help regarding JOIN tables to get category name & author name from other tables.
for articles site I have Three Tables
articles
categories
users
Articles Table structure :
id
title
slug
content
category
author
date
I save category ID & user ID in articles table with each article
While Displaying Articles for a category I use this:
(just some draft idea not full code)
localhost/testsite/category.php?cat=category-slug
$catslug = ($_GET["cat"]);
//GET CAT ID from category table from slug
$qry = "SELECT * from category WHERE slug='$catslug';
$res = mysql_query($qry) or die("Error in Query");
$ans = mysql_fetch_array($res);
$cid = $ans['id'];
$catname = $ans['title'];
<h2><?php echo $catname; ?></h2>
//after getting cat-id query to get article of that ID
$aqry = select * from article where category=$cid ORDER BY date";
$ares = mysql_query($aqry) or die("Error in Query");
$aans = mysql_fetch_array($ares))
$aid = $aans['author'];
//then another query to get author name from users
select username from users where id=$aid
I m learning PHP & not much familiar with JOIN statement & combining queries
need help/suggestions hw can I achieve same with JOIN tables instead of different queries to get catname and author name from tables.
Thanks

This should do what you want
SELECT distinct c.title, U.Username
from category C join article A on A.category=C.id
join users U on U.id=A.author
WHERE C.slug= :catslug

Assuming Category id is foreign jey in article table
Try this query
select username from users
where id in (
select author from category cat
inner join article art
on cat.category_id =art.category_id
where cat.slug= $cat
order by art.date desc )

$q = "SELECT article.*
FROM article
LEFT JOIN category
ON article.category = category.ID
LEFT JOIN users
ON article.author = users.ID
WHERE article.slug = :slug";
:slug is where you would insert (bind if you're using PDO) $_GET['slug']

You can do some different thing with a SQL request. You can do some join in your SQL request but you can also do another SELECT statement in your request Like
SELECT SOMETHINGS FROM A_TABLE WHERE (SELECT ANOTHER_THING FROM ANOTHER_TABLE WHERE VALUE =1
But this statement will only work if you have 1 result in your second request
If you want to join two table with some value, you'll have to do it like this
SELECT something FROM a_table AS alias1 JOIN another_table AS alias2
ON alias1.value1 = alias2.value1 and .....
You can compare all the value that you want from one table to another and you can also join more than two table and the ON key word is not requested by sql syntax you can just do
SELECT * FROM table_1 join table_2
and it will show you all thje data from two table but be sure that this is the data you want this kind of little query can have some big result and slow down your app
you can read more there http://dev.mysql.com/doc/refman/5.0/en/join.html

First off, you should write a stored proc... but here's how you would get articles by categoryID that includes both the category name and user name.
Given the following table structures:
article
---------
articleID <- primary key
title
slug
content
categoryID <- foreign key
userID <- foreign key
createdDT
category
--------
categoryID <- primary key
categoryName
user
--------
userID <- primary key
userName
Here's how to write the query using joins:
SELECT a.title, a.slug, a.content, a.createdDT, c.categoryName, u.userName
FROM dbo.article a
JOIN dbo.category c on a.categoryID = c.categoryID
JOIN dbo.user u on a.userID = u.userID
WHERE a.categoryID = #categoryID
Here's an article from Microsoft on JOINs - http://msdn.microsoft.com/en-us/library/ms191517.aspx

Related

What Sql Join can I use to combine my three tables

I made a query that user can see all the post of active users but not of those inactive, but also they should not see the post of users they blocked or blocked them how can I do that?, the block_users table has block_by_userid and blocked_userid column.
I tried INNER JOIN the post table with members table which every inactive users post cannot be seen anymore., How will I combine the block_users table?
$GetPost = "SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
WHERE Status='active'";
you might try FULL OUTER JOIN
the idea it to get all items in both tables member and block_users and then filter the data using where clause, i am sorry if i miss using the fields name , so please check the tables names, i assume block_users.block_by_userid contained the blocked user id if not use the correct field
$GetPost = "SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
FULL OUTER JOIN block_users ON Members.User_id = block_users.user_id
WHERE Status='active'
AND
WHERE block_users.block_by_userid != Members.User_id";
Suppose I am doing this for a user xyz whose user_id is 123 then below is a query which will return expected output for user 123.
Query:
SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
WHERE Status='active' and post.poster_user_id NOT IN(select block_by_userid from block_users where blocked_user_id = 123 UNION select blocked_user_id from block_users where block_by_userid = 123)

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

Retrieving data from multiple tables mysql php

I have 2 tables MOVIES and SHOWS.
MOVIES tables contains:
id, name, image, description.
SHOWS table contains:
id, movieid, description.
I'm executing mysql statement to retrieve records from SHOWS table, i'm getting all the records normally. Again I'm executing another mysql statement to get image from MOVIES table based on movies table id which i'm getting from first query.
Is there any simple way to retrieve all the records from SHOWS table along with movie image?
These are my queries:
$qry1 = mysql_query("SELECT * FROM shows WHERE id='1'");
$res = mysql_fetch_array($qry1);
$movieid = $res['movieid'];
$qry2 = mysql_query("SELECT image FROM movies WHERE id='$movieid'");
SELECT t1.id, t1.movieid, t1.description, t2.image FROM SHOWS as t1
INNER JOIN
MOVIES as t2 ON t1.id = t2.id
Some sql join docs
or you can try this, i was not sure witch id is from where:
SELECT id, movieid, description, image FROM SHOWS
INNER JOIN MOVIES
ON id = movieid
Some foreign key docs
Here I am writing with out join you can all so use nested select queries
select movies.image from movies where movies.id in(Select shows.movieid form shows where shows.id= 1);
You can retrieve data from multiple tables from one server at the same time. There is a lot of ways to achieve this operation which is called join. One of the possibility would be the LEFT JOIN like this:
SELECT t1.field1, t1.field2,..., t2.field1, t2.field2, ..., t2.fieldn
FROM table1 AS t2
LEFT JOIN talble2 AS t2 ON t2.some_field = t1.anothed_filed
WHERE some_condition
In you case:
SELECT s.*, m.image
FROM SHOWS AS s
LEFT JOIN movies AS m ON s.movieid = m.id
WHERE some_condition
for more info see the documentation on https://dev.mysql.com/doc/refman/5.7/en/join.html

Mysql query, select join two table

I have a LIKE table and a BOOK table and my user_id.
I want to pull only i have liked from BOOK table with BOOK NAMES and AUTHOR
My json will:
{book_id:1,bookname:sample,author:sean,user_id:111}
tables
-----------BOOK TABLE------------
ID ---- BOOK AUTHOR ---- BOOK NAME
1
2
...................................
USERS TABLE
ID-------NAME
1
2
.............
LIKE TABLE---------------------------
ID-----BOOK ID-------LIKER USER ID---
1
2
.....................................
$stmt = $mysqli->prepare("SELECT book.*, users.*, like.* FROM like INNER JOIN
users ON like.liker_user_id = users.id INNER JOIN
book ON like.book_id = book.id WHERE
users.id = ?
");
$stmt->bind_param( "d", $user_id);
$stmt->execute();
$stmt->bind_result($col1);
// then fetch and close the statement
For getting all the data related to likes you can run this sql command.
The result set you can loop and generate the JSON.
Make sure in the query you have all your column names correctly given.
select
b.book_id,
b.bookname,
b.author,
u.user_id
from
`like` l
inner join book b on b.book_id = l.book_id
inner join users u on u.user_id = l.user_id
If you need to filter data just add a where condition after the last JOIN as
where u.user_id = {your user id}

mysql + php foreign key show data

I have 5 tables.
advertisingcompany Table
id PK
name
placement Table
id PK
name
advertiser Table
id PK
name
location Table
id PK
name
ads Table
ad_id PK
size
price
advertisingcompanyId FG
placementId FG
advertiserId FG
locationId FG
I can't figure out how to show foreign key data. I can get for example "advertisingcompanyId" or "placementId" but the problem is to get instead of id the name of advertisingcompany which is in advertisingcompany table or placement name which is in placement table.
I tried with that query:
$query = "SELECT ad_id, size, price, ads.advertisingcompanyId, ads.placementId, ads.advertiserId, locationId
FROM ads
INNER JOIN advertisingcompany ON ads.advertisingcompanyId = advertisingcompany.id
WHERE ad_id = '$ad_id'";
Is that correct SQL query for data I wanted? If it is how can I add to that query I will get name for all foreign keys?
How can I then show that data in php?
Thanks
Is that correct SQL query for data I wanted?
Yes.
If it is how can I add to that query I will get name for all foreign keys?
Specify the name columns that you wish to select and add addiitonal JOIN clauses:
SELECT ads.*,
advertisingcompany.name AS adco,
placement.name AS placement
FROM ads JOIN advertisingcompany ON ...
JOIN placement ON ...
-- etc.
Note that you may wish to use outer joins if some of the foreign keys may be NULL.
How can I then show that data in php?
Connect to MySQL, execute the query, then loop over the resultset:
$dbh = new PDO("mysql:dbname=$dbname;charset=utf8", $username, $password);
$qry = $dbh->query($query);
while($row = $qry->fetch()) print_r($row);
Please be careful to avoid SQL injection attacks by using prepared statements into which you pass user input as parameters that do not get evaluated for SQL! If you don't know what I'm talking about, read the story of Bobby Tables.
SELECT ad_id, size, price,
c.name as company_name,
p.name as placement_name,
a.name as advertiser_name,
locationId
FROM ads
INNER JOIN advertisingcompany c ON ads.advertisingcompanyId = c.id
INNER JOIN placement p ON ads.placementId = p.id
INNER JOIN advertiser a ON ads.advertiserId = a.id
WHERE ad_id = '$ad_id'

Categories