How can I get values from both my tables? - php

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;

Related

Access values with PHP from second table after INNER JOIN

I'm trying to join two tables on their id and then populate an empty array with key - values. table2 has an additional city_name column which I'd like to use.
However, after joining the two tables on their id with INNER JOIN, I cannot seem to access the city_name value from the second table (but getting the values from the first table works fine).
Here's my code:
$city_list = array();
$i = 0;
$q = "SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.city_id";
$res = $mysql_query($q);
while($row = mysql_fetch_assoc($res) {
$city_list[$i]['id'] = $row['id']; // returns the id from table1, which is also identical to the city_id from table2
$city_list[$i]['population'] = $row['city_population']; // returns the city_population value from table1
$city_list[$i]['name'] = $row['city_name']; // returns null, even though the value exists in table2
$i++;
}
When printing the $city_list, I get the appropriate id and population values, but the name key has a value of null, even though I have city names in table2.
Just select the columns you really need.
SELECT table1.id, table1.city_population, table2.city_name
FROM table1
INNER JOIN table2 ON table1.id=table2.city_id
You could select the column names using an alias so that you can access both as you want. eg, change query to something like:
SELECT *, table2.user_name as table2_user_name
FROM table1
INNER JOIN table2 ON table1.id=table2.city_id
Preferably you shouldn't use * if you don't need all the data. It tends to lead to more bugs & more difficult maintenance.

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

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

PHP/SQL Statement repeating a query

If I have a list of ID's that I have selected from a statement
SELECT id FROM myTable WHERE name = 'TEST'
This would return just the ids (1001, 1002, 1003, etc...) Then I want to perform another SELECT statement to retrieve all the titles for all those ids.
SELECT title FROM myTable2 WHERE id = XXXX
the id in table2 is the foreign key of table2. id in myTable is the Primary Key. How can I go about retrieving all the titles from those ids. I was thinking about storing all the results of the first select statement in an array, and then using a while loop to iterate through the list and return each result into another array, but my fear is that when the database gets big if it has to return 1000 rows that could be some bad overhead. So in PHP or SQL what is the best way to perform this?
You can use a subquery:
SELECT title
FROM myTable2
WHERE id IN (
SELECT id
FROM myTable
WHERE name = 'TEST'
)
Another way to do it would to be use a JOIN, to avoid the sub-query:
SELECT title
FROM myTable2
LEFT JOIN myTable
ON myTable.id = myTable2.id
WHERE myTable.name = 'TEST'
You should just be able to select them at the same time.
SELECT a.id, b.title
FROM myTable a, myTable2 b
WHERE a.name = 'TEST' AND b.id = a.id;
to select both:
SELECT id, title FROM mytable WHERE name="TEST"
or to select the whole row
SELECT * FROM mytable WHERE name="TEST"
if its two tables you are selecting from:
SELECT id, title FROM mytable A JOIN mytable2 B USING (id)

Retrieving count of column mySQL PHP

Hey guys I have a mysql table called interests with 4 columns. interestID, name, categoryID interest_desc and date. the categoryID column is linked to a seperate table. How would I use a mysql query that checked how many interests are in a certain category?
Im guessing i use some sort of count() query?
Thanks guys
Update -
$count_query_v1 = "SELECT categoryID, COUNT(*) AS total FROM interests GROUP by categoryID; "; $answer = mysql_query($count_query_v1) or die(mysql_error()); echo $answer;
Getting closer but still not perfect, i want to echo out the categoryID with the most interestID's
select category_name, count(*) as total
from interests i left join category c on c.category_id = i.category_id
group by i.category_id;
count + group by,
assuming interestID is the unique primary key,
and each interest is tied to single category (as what you have shown)
select categoryID, count(*) as total
from interests
group by categoryID;
// the above example is a simple group by ID without using inner join
output :-
categoryID, total
SELECT COUNT(interestID) FROM interests WHERE categoryID = 'yourvalue';
SELECT COUNT(interestID), categoryID FROM interests GROUP BY categoryID;
Since you are using the insert query each query will insert one record, so just count the number of insert queries you run by using a counter varialble.

Categories