How to display content from MYSQL Join if ID is not relational - php

I have an artist page that is supposed to show the albums released by a particular artist.
I am joining two tables to accomplish this. The relation is the artist_name. Both the artist table and the albums tables have different IDs.
Unfortunately, the artist page is showing ALL of the album photos in the database instead of only the ones related to the artist.
My thought process was to to use the $_GET method to grab the artist name which would be included in the URL when the user clicks the link to visit that artist's page. But obviously, this is not working.
Here's my script:
$artist_name = $_GET['artist_name'];
//Query the database to show the albums
$albums = "SELECT artist.artist_name,albums.artist_name,albums.photo,albums.album_title
FROM artist,albums
WHERE artist.artist_name=albums.artist_name
ORDER BY year_released ASC";
$q = $db->query($albums);
$q->setFetchMode(PDO::FETCH_ASSOC);
html:
<?php while ($r = $q->fetch()): ?>
<span class="margin-two album">
<img src="http://mywebsite.com/albums/<?php echo $r['photo']; ?>" alt="picture of the album <?php echo $r['album_title']; ?> by <?php echo $r['artist_name']; ?>" title="<?php echo $r['album_title']; ?>" \>
</span>
<?php endwhile; ?>
How can I output the correct albums for each artist?

Use below query with left join to albums table.
$artist_name = $_GET['artist_name'];
//Query the database to show the albums
$albums = "SELECT artist.artist_name,albums.artist_name,albums.photo,albums.album_title
FROM artist,albums
LEFT JOIN
albums on albums.artist_name = artist.artist_name
WHERE artist.artist_name=$artist_name
ORDER BY year_released ASC";
$q = $db->query($albums);
$q->setFetchMode(PDO::FETCH_ASSOC);
Let me know if you have any question.

Change your $albums string to :
$albums = "SELECT artist.artist_name, albums.photo, albums.album_title
FROM artist
LEFT JOIN albums ON (artist.artist_name=albums.artist_name)
WHERE artist.artist_name=$artist_name
ORDER BY year_released ASC";

Thanks to everyone for pointing me in the right direction with MYSQL LEFT JOIN. After doing a bit more research, I got the following code to work by adding USING in my script.
$artist_name = $_GET['artist_name'];
//Query the database to show the albums
$albums = "SELECT * FROM artist
LEFT JOIN albums
USING (artist_name)
WHERE artist_name='$artist_name'
ORDER BY year_released";

Related

Selecting certain row information from MySql after joining tables

I am building a photo uploading website and I have joined two tables together in order to display the username of the person who uploaded the image. This works but it is printing every name in the database rather than just the image that is selected.
The selected image is called using the following query...
$data = mysql_query("SELECT * FROM photos WHERE id=$imageID");
The following code then attempts to display the username, but I need it to target only the row of the $imageID. How would I do this?
<?php
$query = mysql_query("SELECT username, user_id ".
"FROM users, photos ".
"WHERE (users.id = photos.user_id)");
while($uploader = mysql_fetch_array( $query ))
{
echo $uploader['username']; }
?>
Thanks in advance.
<?php
$query = mysql_query("SELECT username, user_id ".
"FROM users, photos ".
"WHERE (users.id = photos.user_id and photos.id = $imageID)");
while($uploader = mysql_fetch_array( $query ))
{
echo $uploader['username']; }
?>
But this is a little dodgy as you're just substituting a variable straight into your sql and it could be subject to injection attacks. The same goes for your other query.
You should probably look in to using parameterised queries.
You didn't actually narrow down the search result by the ID of the photo in question. I would imagine you want a query more like this:
$data = mysql_query("SELECT u.username, p.user_id FROM users u, photos p WHERE u.id = p.user_id AND p.id = $imageID");

PHP PDO fetch and foreach - I'm not getting the first column

This is my first post, so I'm just getting to know how the community works so I can be helpful too, later on...
I have an index.php and db.php for testing PDO in a very small and simple app, in the first one goes the html and the second the database connection.
index.php
<h1><?php echo $fjoin_bookname; ?></h1>
<?php foreach($join as $j): ?>
<tr>
<td>
<?php echo 'Page: '. $j['pageNumber']; ?>
</td>
<td>
<?php echo $j['pageNote']; ?>
</td>
</tr>
<?php endforeach; ?>
db.php
//get books and pages Join
$query='SELECT *
FROM books
INNER JOIN pages
ON books.bookID = pages.bookID
ORDER BY pageNumber ASC';
$join = $db->query($query);
$fjoin = $join->fetch();
$fjoin_bookname = $fjoin['bookName'];
It is an app that gets page numbers with a corresponding note from a book, this will help to keep track of several books while on different devices.
Problem:
I'm not getting the first row from the 'pages' table.
It was working fine until I inserted the fetch method
$fjoin = $join->fetch();
$fjoin_bookname = $fjoin['bookName'];
Question
Would anyone be so kind to help me work this out?
When you do a call of
$join->fetch()
it returns item from current position and move cursor to the next one.
You can fetch all elements to a var and then get fjoin_bookname from the first element:
db.php
//get books and pages Join
$query='SELECT *
FROM books
INNER JOIN pages
ON books.bookID = pages.bookID
ORDER BY pageNumber ASC';
$statement = $db->query($query);
$join = $statement->fetchAll();
$fjoin = $join[0];
$fjoin_bookname = $fjoin['bookName'];

MySQL/PHP - Nested Select Issue - Need To Obtain Values From Both Tables

I just need help refining this script to give me the values from both tables joined on the ID.
Basically I want the ID from both tables and then be able to get the other values from both tables based on the IDs (if need be) and display them in a loop.
The code I have is below but won't work.
$select = myQ("SELECT * FROM users a WHERE EXISTS (SELECT 1 FROM `videos` b WHERE a.id = b.id GROUP BY b.id HAVING count(*) > 1) ");
$i=0;
while ($row = myF($select)) {
$resultsLoopArray[$i]["videos.id"] = $row["id"];
$resultsLoopArray[$i]["videos.vid"] = $row["vid"];
$resultsLoopArray[$i]["users.username"] = $row["username"];
$i++;
}
if (isset($resultsLoopArray)) {
$tpl->Loop("searchResultsLoop", $resultsLoopArray);
}
For now all I need is the username from the users table, the id and video id from the video table.
Can someone help by chance?
you question is bit confusing me..
As for my understanding I am posting this soultion..
If you have two tables users , videos then .
$sql = "SELECT users.username , videos.* from users, videos where users.user_id = videos.user_id";
this query will fetch all record from users and videos table where user id is present in videos tables ...

Select from one table, and count from another table in same query

I have quite a bit of knowledge about SQL queries.
I'm trying to make gallery, and I need to select categories from table "cat_photos", which contain rows (id,name,cover,photo) and count number of photos from table "photos" which contain rows (id,thumb,photo,category).
Here is code which i use:
1) Selecting categories
$query = mysql_query("SELECT * FROM cat_photos ORDER BY ID DESC");
while($data = mysql_fetch_array($query)) {
echo "<li><a href='photos.php?cat=$data[id]'><img src='galleries/categories/$row[image]' alt='$row[name]' /></a>
<div class='photodesc'><div class='catname'><a href='photos.php?cat=$row[id]'>$row[name]</a></div>
<div class='catcount'>Number of photos in category</div></div></li>"; }
2) Counting number of photos in category
$query = mysql_query("SELECT category, COUNT(photo) FROM photos GROUP BY category") or die(mysql_error());
while($row = mysql_fetch_array($query)){
echo "Number of photos is ". $row['COUNT(photo)'] ." in cateogry ". $row['category'] .".";
echo "<br />"; }
Separated all works, but I can't find a way to merge them into one query.
I have googleing for "UNION", "JOIN", "LEFT JOIN" options in MySql query but I could't together the pieces.
I wonder if this is in general possible?
How in order that query look like?
Try this, it should work :
SELECT cat_photos.*, count(photos.id) as number_photos
FROM cat_photos
LEFT JOIN photos ON photos.category = cat_photos.id
GROUP BY cat_photos.id, cat_photos.name, cat_photos.image
ORDER BY cat_photos.id
The number of photos will be accessible trough $row['number_photos'].
Just use your second query and join the wanted category elements.
Something quick and dirty would be:
SELECT c.category, COALESCE(COUNT(p.photo),0) as photos FROM photos p, cat_photos c
WHERE c.category = p.category
GROUP BY category
Since I don't know your exact database setup just change the selected elements to the ones you really need.
//edit: Put in Coalesce to get categories with 0 photos.
Don't SELECT *. Instead select individual columns and then join:
SELECT
cat_photos_main.id, cat_photos_main.category, cat_photos_main.photodesc, cat_photos_counts.num_photos
FROM cat_photos cat_photos_main
LEFT OUTER JOIN (SELECT category, count(*) AS num_photos FROM photos GROUP BY category) cat_photos_counts
ON cat_photos_main.category = cat_photos_counts.category

How do i GROUP BY or DISTINCT inside array?

I have searched high and low and cant find a similar issue to what i have.
I am a beginner so please forgive my clunky query structure.
I am trying to ( have attached screen grab below of output ):
Query the photos table to get the id based on category id and also start,limit because of pagination.
Query the photos tagged table based on the photo id i just got from the first query.
But my problem is that i cant group the tags, some photos have the same tag name. And the output just shows all the tags for each photo. I want restaurant to show only once etc...
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id']." GROUP BY tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($rowTagged = mysql_fetch_array($resultTagged)) {
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php }} ?>
the above query is producing:
bar,cappucino,coffee,coffee machine,restaurant,bar,cappucino,coffee,coffee machine,restaurant,bar,coffee,restaurant,bar,coffee,coffee machine
restaurant,bar,cappucino,coffee,restaurant
what i need to show is:
bar,cappucino,coffee,coffee machine,restaurant
If anyone could help i would greatly appreciate it.
Thank you in advance.
John
My new code is
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged);
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php } ?>
I now get this: ( So i am close arent i? )
----------
cappucino
restaurant
bar
coffee machine
restaurant
coffee
coffee
restaurant
restaurant
restaurant
coffee
coffee
restaurant
restaurant
coffee machine
restaurant
coffee
I wonder if the spaces are something? i got that from copy and paste...
Any further help would be appreciated :-)
You should first perform a join between your photos and tags table, and THEN select the distinct tags.
I believe this query will let the database do all the work for you:
SELECT DISTINCT tag_name
FROM (SELECT file_id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) t1
LEFT JOIN photoTagged ON t1.id = photoTagged.file_id
You can also sort the tags in the database (ORDER BY tag_name).
Haven't tried it myself, so maybe the syntax is a bit off. But the idea should work.
distinct doesnt work if you are only getting one record at a time, so put the data in a PHP array and then use array_unique, which is PHPs way to do distinct
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged)
$tagged[] = $rowTagged['tag_name'];
}
// Let PHP do the work.
$tagged=array_unique($tagged);
while (list(,$val) = each($tagged)) {
echo "<li><a href="#">$val</li>
}
?>
you need to do a sub-query to dodge the pagination problems with the photos. If you wish the selected tags to be a subset of the photos found in your first query, then you will need to do the following.
<?php
$queryTagged = "SELECT TAG.tag_name, count(TAG.tag_name) AS num FROM photoTagged as TAG JOIN (SELECT id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) as PHOTO ON (PHOTO.id = TAG.file_id) GROUP BY TAG.tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($tagged = mysql_fetch_assoc($resultTagged)) {
echo "<li id="'.$tagged['TAG.tag_name'].'"><a href="#">".$tagged['TAG.tag_name']." (".$tagged['TAG.num'].")</li>";
}
?>
This way you will have two queries, on for finding the photos, and one for finding the tags for the photos on that page. This technically takes a little longer as MySQL has to load the query into a temporary table, but it should work fine.
SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'] ?

Categories