I'm actually not too sure if I even need a join. It's really the only thing while learning SQL that I didn't really understand or pay attention too, but basically I have 2 tables:
games
subgames
In games I have gamesname row:
Final Fantasy
Metal Gear Solid
Yu-Gi-Oh
In subgames I have subgamesname row:
Metal Gear Rising
They both have autoincrement for an id. However I am trying to display my games as clickable links then refreshes the page and shows the subgames. So for example if I clicked Metal Gear Solid it would take you to games.php?subgame=Metal%20Gear%20Solid and show Metal Gear Rising. Here is what I have so far, but it does not show Metal Gear Rising, probably because I have the games in one table and sub games in another with no reference to each other.
So my question is, how can I reference them in my code to display properly?
<?php
$sub = $_GET['subgame'];
if($sub){
$result = mysql_query("SELECT $sub FROM games");
while ($row = mysql_fetch_array($result)) {
printf("%s<br />", $row["subgamename"], $row["subgamename"]);
}
}
else{
$result = mysql_query("SELECT gamename FROM games ORDER BY gamename");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("<a href='games.php?subgame=%s'> %s </a><br />", $row["gamename"], $row["gamename"]);
}
}
?>
Your query it's wrong. What is:
$result = mysql_query("SELECT $sub FROM games"); ????
it should be
mysql_query("SELECT subgamesname FROM subgamesname where gamesName ='".$_GET['subgame']."'");
But your name of parameter it's not intuitive subgame, it's should be gameName because you search through games name
The query you probably want is:
$sub = mysql_real_escape_string($_GET['sub']);
$query = "
SELECT subgamesname
FROM subgames s
JOIN games g ON g.id = s.game_id
WHERE g.gamesname = '$sub'
";
I'm assuming the subgames table has a game_id column that's a foreign key to the games table. You need to replace those column names with what you're actually using in your schema.
Related
I have a problem with this MySQL Statment. So basicly i have a table called games and i want to
display this table on my website. Table games has Foregin Keys like developer_id,
publisher_id, categorie_id, platform1_id, platform2_id, platform3_id, platform4_id, platform5_id.
I have 5 of platform because in Table platforms i have 5 records (PC, PS4, XB1, SWITCH, MOBILE). (If you guys know any better and easier solution to these platforms pls tell me.)
So now my output on my website works but for example instead of showing developer name it shows
it's ID. I know i have to INNER JOIN them and i probbably can INNER JOIN all foregin keys but the
platform one. Because i dont know how to INNER JOIN if you have more then one FK from one table.
If you need more info tell me. I will also include picture of my DB and my PHP code where i SELECT from table games.
$query = "SELECT * FROM games WHERE id = $id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'.$row['developer_id'].'</td>';
echo '<td>'.$row['publisher_id'].'</td>';
echo '<td>'.$row['categorie_id'].'</td>';
echo '<td>'.$row['platform1_id'].'</td>';
echo '<td>'.$row['platform2_id'].'</td>';
echo '<td>'.$row['platform3_id'].'</td>';
echo '<td>'.$row['platform4_id'].'</td>';
echo '<td>'.$row['platform5_id'].'</td>';
echo '<td>'.$row['game_name'].'</td>';
echo '<td>'.$row['relese_date'].'</td>';
$intro = $row['introduction'];
$desc = $row['description'];
echo '<td>'.$row['rating'].'</td>';
echo '</tr>';
}
Picture of my DataBase
SELECT games.game_name, games.relese_date, games.introduction, games.rating, games.description, dev.name as developer, pub.name as publisher, (SELECT * FROM platforms WHERE platforms.id in (games.platform1_id,games.platform2_id,games.platform3_id,games.platform4_id,games.platform5_id)) as plats
FROM games
INNER JOIN developers AS dev ON dev.id = games.developer_id
INNER JOIN publishers AS pub ON pub.id = games.publisher_id
WHERE games.id = $id
Keep in mind that the platforms will be listed as a collection under the property plats, and each of those items will be an object of properties as.
E.X.
return object=>
developer_id
publisher_id
categorie_id
plats => [
platform1_id=>name,
platform2_id=>name,
platform3_id=>name,
platform4_id=>name,
platform5_id=>name
]
game_name
relese_date
introduction
description
rating
I am trying to pull a list of genres from the database. I enter a list of genres into the database for each song, and then it (is supposed to) pull each song's genre into a list and order them by the top three most common occurrences.
The genres get put into a single text field in such a fashion:
(basic fashion, not an actual result):
blues rock, garage rock, hard rock
Here's my code:
$sql = "SELECT `song_name`, `song_genres` FROM `songs` WHERE `album_id` = '$songAlbumId'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$song_name = $row['song_name'];
$song_genres = explode(", ", $row['song_genres']);
for ($i = 0; $i < count($song_genres); $i++){
$count=array_count_values($song_genres);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo $keys[$i] . "<br>";
}
}
This ends up giving me:
Hard Rock
Garage Rock
Hard Rock
Garage Rock
Psychedelic Rock
Blues Rock
Garage Rock
Hard Rock
Also note there is nothing wrong with the album id or anything else. It is specifically to do with just the genres being ordered right.
Normalize the genres. Use a genres table instead of a comma separated list, and an additional songs_genres table to link songs to genres. Then you can get the data from the database without further logic in php
SELECT g.name, COUNT(DISTINCT(sg.song_id)) cnt
FROM genres g
INNER JOIN songs_genres sg ON sg.genre_id = g.id
GROUP BY g.name
ORDER BY cnt DESC
LIMIT 3
You need another loop so your genres echo for each songname
while ($row = mysqli_fetch_array($query)){
$song_name = $row['song_name'];
$song_genres = explode(", ", $row['song_genres']);
foreach($song_name as $songname){
for ($i = 0; $i < count($song_genres); $i++){
$count=array_count_values($song_genres);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo $keys[$i] . "<br>";
}
}
}
I spent a couple days trying to figure it out. I ended up reworking the database and posting the songs genres into a database for the song, album, and band sections to easily pull from.
For anyone in the future who wants help with a problem like this, the solution is here: Merge multiple arrays into one array.
I appreciate the input from the other people though.
Thanks in advance for any time you spend on my question.
I am trying to display data in a way that will display the manufacturer as a name instead of a number.
Basically when they store the data they choose a manufacturer from a drop down which is generated from a table.. IE Trogues = 1 so products stores the #1 so I know that any beer is associated with trogues is 1. Now I want to display the data but instead of having a 1 I would like to have Trogues be displayed. Where you see manufacturer in the echo code below..
I am not understanding the process logic here..
error_reporting(E_ALL);
ini_set('display_errors', 1);
$sql = "SELECT * FROM products
LEFT JOIN manufacturer
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
<div class=reportclientproduct>".$row['manufacturer']." - <a href=".$row['website']." target=_blank>".$row['product']."</a></div>";
}
Have you tried the query like this:
$sql = "SELECT man.id AS manufac, products.product AS prod FROM products
LEFT JOIN manufacturer as man
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
".$row['manufac']." - ".$row['prod']."
";
}
Assuming that the table products had a column named manufacturer which holds the ID of the manufacturer, and that both tables have columns name ID which hold the ID of the table item.
Also the JOIN functions may vary based on the database you use. But the aforementioned method is for mysql.
Hi i have a social networking website.
what i want it to do is pull out my friends status updates.
basically what it does is i have a mysql query that pulls out all of my friends and in that while loop there is another mysql query that pulls out the status's from my friends.
i want it to be in order of date but since its one while loop in another what it does is pull out all status's from friend 1 then 2 then 3 and not in order by date. i even tried ORDER BY DATE but that just ordered it by date within the friend..
my thought is that i could putt it all in an array and friends is one thing and the values is the stats. then just sort by values would this work and how could i do it.
the friend and stats are in two differants tables
THANKS SO MUCH
CODE:
$friendssql = mysql_query("SELECT * FROM friends WHERE sender='$id'");
while($row = mysql_fetch_object($friendssql)) {
$friendid = $row-> accepter;
$frsql = mysql_query("SELECT * FROM myMembers WHERE id='$friendid'");
while($rowa = mysql_fetch_object($frsql)) {
$ufirstname = $rowa-> firstname;
$ulastname = $rowa-> lastname;
}
$blabsql = mysql_query("SELECT * FROM blabbing WHERE mem_id='$friendid' ORDER BY blab_date DESC");
while($rowb = mysql_fetch_object($blabsql)) {
$blab = $rowb-> the_blab;
$blabd =$rowb-> blab_date;
$ucheck_pic = "members/$friendid/image01.jpg";
$udefault_pic = "members/0/image01.jpg";
if (file_exists($ucheck_pic)) {
$blabber_pic = "<img src=\"$ucheck_pic\" width=\"50px\" border=\"0\" />"; // forces picture to be 100px wide and no more
} else {
$blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more
}
Once you've put your data into the array, you could take a look at some of the various array sorting functions in PHP: http://php.net/manual/en/array.sorting.php
why not do it all in one query? this is psuedo sql, so you'll have to modify with your real tables and relationships.
select f.name,s.statustext
from friends f
inner join status s
on s.friend_id = f.id
inner join myfriends mf
on mf.friend_id = f.id
where mf.myid = 'myid'
order by f.name, s.datestamp
or something similar.
The code below works great. I have a MySQL database that contains book titles classified in different categories. In the code below, the variable "site" represents a book title. Each category is represented by a different table in the MySQL database.
The code below ranks the top 25 book titles (site) by total votes across all categories (MySQL tables). I am trying to exclude blank book titles (i. e. when site = ''). How can I do this?
I have tried inserting WHERE site != '' in a few places but I get an error message. So I guess I'm asking, where can I insert WHERE site != ''?
Thanks in advance,
John
<?
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$result = mysql_query("SHOW TABLES");
$tables = array();
while ($row = mysql_fetch_assoc($result)) {
$tables[] = '`'.$row["Tables_in_bookfeather"].'`';
}
$subQuery = "SELECT site, votes_up FROM ".implode(" UNION ALL SELECT site, votes_up FROM ",$tables);
// Create one query that gets the data you need
$sqlStr = "SELECT site, sum(votes_up) sumVotesUp
FROM (
".$subQuery." ) subQuery
GROUP BY site ORDER BY sum(votes_up) DESC LIMIT 25";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"samples2\">";
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td class="sitename2">'.$row["site"].'</td>';
echo '<td>'.$row["sumVotesUp"].'</td>';
echo '</tr>';
}
echo "</table>";
?>
You shouldn't have separate tables for each book category. I can't believe you have so many books that any of these tables would grow too large. Any scalability benefits you might gain by splitting the table are offset by the complexity of having to do these UNION queries.
Here's what I'd do:
Unify the tables into one table.
Add a Categories table.
Relate books to categories with a many-to-many table.
Then your SQL query becomes much simpler:
$sqlStr = "SELECT site, votes_up FROM Books
WHERE site IS NOT NULL AND site <> ''
ORDER BY votes_up DESC LIMIT 25";
It's probably safest to put it in the subquery:
$subQueryParts = array();
foreach($tables as $table)
$subQueryParts[] = "SELECT site, votes_up FROM $table WHERE LENGTH(site)";
$subQuery = implode(" UNION ALL ", $subQueryParts);
If possible, you should follow Bill Karwin's advice and store all your books in one table. Dynamic table names are very hard to search and manage, and they do not optimize well.