mysql + php foreign key show data - php

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'

Related

PHP Join Query for Three Table When There is No Direct Common Column?

I have Three Tables in which first two tables have common column to match the record, and 2nd and third table also have common column but there is no direct matching column in first and third table. How shall I write join query ?
Table1(order) Column Names are order_id, patient_id, total, discount
Table2 (order_details) Column Names are order_details_id, order_id, test_id, result
Table3(tests) Column Names are test_id, test_name, test_normal_value
I hope it helps
SELECT * FROM `order`
LEFT JOIN `order_details` ON `order`.`order_id` = `order_details`.`order_id`
LEFT JOIN `tests` ON `order_details`.`test_id` = `test`.`test_id`
"SELECT a.patient_id FROM table1 as a
LEFT JOIN table2 as b on a.order_id = b.order_id
LEFT JOIN table3 as c on c.test_id = b.test_id";
to join this 3 table in one query, we need to assign each table a name. For example table1 AS NewNameTable1 LEFT JOIN table2 AS NewNameTable2. To connecting between this 3 table we need to have a foreign key for each table. So that this 3 table able to JOIN and we able to fetch the data in single query. As long this 3 table is JOINED via foreign key, you can echo out any attribute from any table that Joined.

SQL query from 2 tables (1 is key table)

PHP
Tables are:
I have 2 tables, one of trips and the other is key table (index,type)
I want to receive all the names of the trips that the index of the trip type is 1 (output = Alexander)
I receive into variable "$Trip_Type" the user's choice and in addition I need to add to the query another condition of variable $Trip_Population, that has a key table for his values named "Population". How can I combine this in the query?
"Population" is a key table like "Types": 1. index, 2. Type. In addition there is a column "Population_Type" in table Trips. I need all in 1 query
I have this query and I need to add for this the Population condition:
$query = "SELECT trips.Trip_Num
FROM trips JOIN trip_types ON trips.Trip_Type = trip_types.Type
WHERE trip_types.type = " . $Trip_Type;
select t1.name
from trips t1
inner join types t2 on t1.type =t2.type
$sql=
"SELECT t.name
from trips t
JOIN types ty ON t.type = ty.type
WHERE ty.type = " . $Trip_Type;
SELECT a.name
from trips a
JOIN types b ON t.type = a.type
WHERE b.type ='$Trip_Type'
I assume you are use php code to execute this query

How can I get values from both my tables?

Let's say I have to MySQL tables like this.
TBL_1
ID - NAME - DESCRIPTION
1 foo very nice
TBL_2
ID - PRICE - CATEGORY - QUANTITY
1 10 a 5
If I was to set up a PDO instance like so....
<?php
$handler = new PDO("XXXX;XXXXX","XXX","XXX");
$query = $handler->query('SELECT * FROM TBL_1');
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->id;
echo $r->name;
echo $r->description;
//echo $r->price;
//echo $r->category;
//echo $r->quantity;
}
How can I access price, category, quantity where the ID's, in both tables are equal to each other?
So for example, it would come out like this.
1 foo very nice 10 a 5
You might use JOIN:
SELECT name, description, price, category, quantity
FROM TBL_1
JOIN TBL_2
USING (id)
Hope it helps.
Assuming the ID columns contain the same values (i.e. a foreign key constrait exists because the values represent the same entity), you'll want to execute a query with an INNER JOIN on that column. By default with an INNER JOIN, if the requested value (for instance a WHERE 'ID' = 3 clause) does not exist in either table, no results will be returned. Try the following:
SELECT *
FROM `TBL_1` AS `t1`
INNER JOIN `TBL_2` AS `t2` ON `t1`.`ID` = `t2`.`ID`;
You just do an INNER JOIN on the table where on each table the id is equal.
SELECT * FROM TBL_1 INNER JOIN TBL_2 ON TBL_1.ID=TBL_2.ID;

mySQL Return field names from multiple foreign keys

I'm new to mySQL and was hoping to get some help. I have a table layed out in the following way:
TASK
task_id *
tasktype_id (FK)
proj_id (FK)
empl_id (FK)
taskstat_id (FK)
hrs
notes
If I do a query like this, the results print out fine but the numeric references to foreign keys are printed.
SELECT * AS task FROM task
INNER JOIN tasktype ON tasktype.tasktype_id = task.tasktype_id
WHERE taskstat_id = 1";
But I would like to print out the field names instead of field numbers for the foreign keys in the resulting table. Any ideas? This is what I tried, but without any luck.
SELECT task.task_id,
tasktype.tasktype_id,
project.proj_id,
employee.empl_id,
taskstatus.taskstat_id,
task.hrs,
task.note
FROM task, tasktype, project, employee, taskstatus
INNER JOIN tasktype ON tasktype.tasktype_id = task.tasktype_id
WHERE task.taskstat_id = 1";
well, assuming the "field name" in the related tables (column name) is called... name (I don't know the structure of your joined tables)
select t.task_id,
tt.name, //or tt.description, or whatever
p.name, //same
e.name, //same
ts.name, //same
t.hrs,
t.note
FROM task t
inner join tasktype tt on tt.tasktype_id = t.tasktype_id
inner join project p on p.proj_id = t.proj_id
inner join employee e on e.empl_id = t.empl_id
inner join taskstatus ts on ts.taskstat_id = t.taskstat_id
where t.taskstat_id = 1

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

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

Categories