MySQL: How to store/retrieve artist information? - php

It's very confusing; it seems like I'll need to have at least one many-to-many relationship.
A track might be sung by 2+ artist - how can I store that in the database?
While showing that track, I want link to each artist so that when users click the track it opens that artist's profile page.
Can anyone provide me with some assistance in designing a class or classes to accomplish this?

Try something like that
tblSongs
SongId
Title
YearProduced
etc.
tblArtist
ArtistId
Name
ProfilePage
etc..
tblSongArtists
SongId
ArtistId
Then your queries could look something like
SELECT Title, YearProduced, Name, ProfilePage
FROM tblSongs S
LEFT OUTER JOIN tblSongArtists SA ON SA.SongId = S.SongId
LEFT OUTER JOIN tblArtists A ON A.ArtistId = SA.ArtistId
WHERE Title = 'I got the blues' -- ....
ORDER BY SongId -- or Song Title (*)
(*) order by clause is in case the search criteria produces more than one song, and if you wish to keep the artists for a given song in sequence.
Such a query produces multiple rows for a song with several artists, one row per artists, the values of the columns from tblSongs being repeated.

Any many-to-many relationship requires three tables. For your example:
Song<br/>
Name SongID
Artist <br/>
Name ArtistID
ArtistsInSongs <br/>
ArtistID SongID
I'll let you figure out the rest.

public static function find_artist_on($track_id=0) {
global $database;
$sql = "SELECT * FROM " . self::$table_name ." s " ;
$sql .= "LEFT OUTER JOIN trackartist TA ON TA.track_id =s.track_id";
$sql .= "LEFT OUTER JOIN artist A ON A.artist_id =TA.artist_id";
$sql .= " WHERE s.artist_id=" .$database->escape_value($track_id);
$sql .= " ORDER BY artist_id ASC";
return self::find_by_sql($sql);
}

Related

Count how many of each value from a field with MySQL and PHP

I've seen that question several times but I can't find out how to display the result. I have a movie database and I would like the count of each genre of movie in my top menu in a single MySQL query so my menu would display like this:
Total Movies (300)
Drama (50)
Comedy (75)
Thriller (30)
...and so on...
I've found some MySQL query on this site but no one specify HOW to handle the counts after the SQL query. Something like this would probably work:
select genre, count(*) from movies group by genre
But how do I display the count for each value afterwards?
Thank you very much!
Alias the count part so you have an easily accessible column name:
SELECT genre, count(*) AS nb_movies FROM movies GROUP BY genre
then you can access it like $row['nb_movies'].
Without the alias the aggregate column takes the name of the aggregate function call which produced it, so in your case it would be accessed like $row['count(*)'].
Try
select genre, count(*) AS total from movies group by genre
Use total as your count for eg.
echo $result['total'];
Try this,
SELECT genre, count(*) AS total_genre_movies FROM movies GROUP BY genre
Now you can access like $result['total_genre_movies']
It's easier if you alias the result of count(*)
select genre,
count(*) as total
from movies
group by genre
Then you can access it as $row['total'] when you fetch the result into $row in exactly the same way you'd reference $row['genre']
select genre, count(*) as genre_count from movies group by genre
Now you can access like $result['genre_count']
Try this,
$result = mysql_query("select genre, count(*) as genre_count from movies group by genre");
while($row = mysql_fetch_array($result)) {
$genre = $row['genre'];
$genre_count = $row['genre_count'];
}

PHP MySQL - Select members with where-clause statements from different tables

I've been Googling for most of my day now but I can't seem to find the right answer. Maybe because I don't really know in which direction to look (join? exist?). What I have is 3 tables:
There is a table named 'groups' and 'languages' containing the actual group- and language data but that's not important right now.
The user should be able to generate a list with all members, depending on the selected groups and/or languages. The groups/languages that the user selected are saved in two separate array's containing the IDs ($aGroups and $aLangs).
What I want/need is to SELECT * FROM members WHERE ...
And that's where I got stuck. I've tried joins, I've tried IN(), I've tried EXIST but nothing seems to work right.
Any help is greatly appreciated!
If you want to select members by languages and groups, you can do something like this :
$query = "select * from members as m
left join group_members as gm on gm.member_id = m.id
left join language_members as lm on lm.member_id = m.id";
if(isset($aGroups)) {
$query .= " where group_id in (".implode(",", $aGroups).")";
if(isset($aLangs)) {
$query .= " and language_id in (".implode(",", $aLangs).")";
}
}
elseif(isset($aLangs)) {
$query .= " where language_id in (".implode(",", $aLangs).")";
}
I think you just need some brackets:
//assuming you have ids stored in $lang and $group
SELECT * FROM members WHERE (SELECT group_id FROM group_members WHERE member_id=members.id)='$group'
AND (SELECT lang_id FROM language_members WHERE member_id=members.id)='$lang'
The trick is "members.id", DB will call subquery for every member to find out if the condition for group and lang is met.
Select m.* FROM members m, group_members gm, language_members lm
WHERE
lm.member_id=m.id AND
m.id=gm.member_id AND
<<<< START YOUR OWN WHERE HERE.

MySQL search with joins and match

I've got one table filled with information about companies (tblforetag) in Sweden, one table with provinces (tbllan) and one table with cities (tblstad). The cities are linked to the provinces with id numbers and the company table has a column for the city name (varchar).
How do I search for all the companies in one province?
I have fiddled around with joins but not got it to work. I've got this code right now that works but it will only search for company names and cities (in the company table):
$sql = "
SELECT *,
MATCH(tblforetag.foretag) AGAINST(:keywords) AS kr
FROM tblforetag
WHERE MATCH(tblforetag.foretag) AGAINST(:keywords)
";
$sql .= $locisset ? "AND tblforetag.stad LIKE :location" : "";
$sql .= " LIMIT $offset, $rpp";
$query = $conn->Prepare($sql);
$query->BindValue(':keywords', $keywords);
if($locisset) $query->BindValue(':location', "%$location%");
$query->Execute();
I do not know your table structure but something along these lines shoulod do the trick:
SELECT FROM companies
LEFT JOIN cities ON (companies.city_id = cities.id)
LEFT JOIN regions ON (cities.region_id = regions.id)
WHERE region.name = 'your region'
This would give you the companies in that particular region.
I think it would be better the city_name column in companies table to city_id.
SELECT a.*, p.provincename
FROM companies a, cities c, provinces p
WHERE a.city_name = c.city_name
AND c.city_id = p.city_id
AND p.province_id = 5 // give your province id here

Echo results of a complicated INNER JOIN query with multiple tables

This is my first question here. I have a complicated SQL database and I need to join different tables which have the same column names.
"event" is a sports match. It contains tournament_stageFK which is linked to tournament_stage table, which contains tournamentFK which is linked to tournament table, which contains tournament_templateFK which is linked to tournament_template table, which contains sportFK which is linked to sport table.
So in order to find out what sport the match is from, I need to do an inner join, otherwise I'd have to open the database millions of times. The only way to do it is this, but I don't know how to display the results. My poor attempt to echo the results is below:
$SQL = "SELECT sport.name,
country.name,
tournament_template.name,
tournament.name,
tournament_stage.name,
event.*
FROM tournament_template
INNER JOIN sport
ON tournament_template.sportFK = sport.id
INNER JOIN tournament ON tournament.tournament_templateFK = tournament_template.id
INNER JOIN tournament_stage ON tournament_stage.tournamentFK = tournament.id
INNER JOIN event ON event.tournament_stageFK = tournament_stage.id
INNER JOIN country ON tournament_stage.countryFK = country.id
WHERE DATE(event.startdate) = CURRENT_DATE()
ORDER BY sport.name ASC,
country.name ASC,
tournament_stage.name ASC,
event.startdate ASC";
$result = mysql_query($SQL);
while($get=mysql_fetch_array($result))
{
echo $result['event.name'];
echo "<br>";
}
Your result is fetched as an array indexed by column name, which is "name" for several of your columns... the table name sport, country, template, etc is not part of the returned index. So you need to provide column names that will be unique
Set an alias for each of your columns (e.g. SELECT sport.name AS sport_name) then reference it by its alias within your echo (e.g. $result['sport_name']).
You need to use column aliases and access those in your fetch call. Instead of event.*, be explicit about the columns you need:
$SQL = "SELECT sport.name AS sportname,
country.name AS countryname,
tournament_template.name AS templatename,
tournament.name AS tournamentname,
tournament_stage.name AS stagename,
/* Use explicit column names instead of event.* */
event.name AS eventname,
event.someothercol AS someother
FROM tournament_template
...etc...
...etc...";
// Later...
while($row=mysql_fetch_array($result))
{
echo $row['eventname'];
echo "<br>";
}

Relational Database query MySQL

I have modified the names of my Tables. The sportevents table is the main table and it should get its data from the tables: event_date, events, results, and members. Is there a way to do this. Please not i need to keep this structure.
sportevents (link table)
• id
• event_id
• date_id
• result_id
event_date
• id
• date
events
• id
• eventname
results
• id
• result
members
• id (the ID number of a person)
userlogin
• id
• username
• password
I have managed to get it right without joins. The following:
$query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ".
"WHERE userlogin.username = '$un' " .
"AND sportevents.id = members.id " .
"AND sportevents.event_id = event.id " .
"AND sportevents.date_id = dates.id " .
"AND sportevents.result_id = results.id";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo $row['eventname'];
echo " - ";
echo $row['year'];
echo " - ";
echo $row['result'];
}
Gives me this:
Karoo Cycle - 2008 - 1h14mins
I presume that you have member's data stored in to $_SESSION['member'] or smth. And i dont know exactly why you have separated tabes on event, event_date (there should be one in my perspective) and I guess that main_events is something like event's group/category.
and you are missing MEMBER - EVENT link. add field 'member_id' to the events table.
If that's what it is then it's something like that.
$q = 'SELECT e.*, ed.year, r.result FROM events As e
LEFT JOIN event_date As ed ON ed.id = e.id
LEFT JOIN result As r ON r.id = e.id
WHERE e.member_id = ' . $_SESSION['member']['id'];
from that you get
event id, event name, event year, result. "JohnSmith" you can get from $_SESSION['member'].
If you decide not to use separate tables for event, event_date, result and use only one table with more fields u can do this without any LEFT JOINS just very simple SELECT query.
First, you need to link event with a result. It depends on your domain model, but I'll assume you have only one result per event, so I'll add result_id to the events table. Also, you need to link members with events somehow, I'll use
events_members
member_id
main_event_id
table. With this vcersion you'll be able to have multiple members participate in multiple events.
And finally, the query would be something like the following:
select m.username, e.eventname, y.year, r.result
from members m
join events_members em on em.member_id = m.id
join main_events me on em.main_event_id = me.id
join event e on e.id = me.event_id
join year y on y.id = me.year_id
join result r on r.id = e.result_id
where m.username = $username

Categories