Why is my 3 table JOIN MySQL query not working? - php

I have 3 tables:
Table: album
Columns: id, name, description, author, path, image
Table: albumconnect
Columns: id, imageid, albumid
Table: albumimages
Columns: id, path
And I'm trying to replace all those unnecessary queries with a single JOIN query:
<?php
$albumID = $_SERVER['QUERY_STRING'];
$realAlbumID = substr($albumID, 1);
$realestAlbumID = str_replace('%20', ' ', $realAlbumID);
$sql = "SELECT * FROM album WHERE id='$realestAlbumID'";
$result = mysqli_query($conn, $sql);
$getResult = mysqli_fetch_assoc($result);
$albumPath = $getResult['path'];
$sql2 = "SELECT * FROM albumconnect WHERE albumid='$realestAlbumID'";
$result2 = mysqli_query($conn, $sql2);
while ($row = $result2->fetch_assoc()){
$imageId = $row['imageid'];
$sql3 = "SELECT * FROM albumimages WHERE id='$imageId'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
$imagePath = $getResult3['path'];
echo '<div class="imageContainerAlbums"><li class="listAlbums"><img class="specificAlbumThumnails" src="'.$albumPath.$imagePath.'" alt="Random image" /></li></div>';
};
?>
Now the JOIN query I've come up with based on stuff I've read online is this:
$sql5 = "SELECT * FROM album
JOIN albumconnect ON albumconnect.albumid=album.id
JOIN albumimages ON albumimages.id=albumconnect.imageid
WHERE id='$realestAlbumID'";
$result5 = mysqli_query($conn, $sql5);
However, when I try to var_dump the contents, it prints Null so I assume my query is incorrect but I can't figure out the correct way to do it.

Should be something like this. I didn't test it. As #Difster correctly said, SQL engine doesn't know which id should it reference. So, define table aliases and prefix the referenced columns with them. Then define unique aliases for the column names too. Otherwise your sql statement were almost perfect.
<?php
$albumID = $_SERVER['QUERY_STRING'];
$realAlbumID = substr($albumID, 1);
$realestAlbumID = str_replace('%20', ' ', $realAlbumID);
$sql = "SELECT
alb.name AS album_name,
alb.description AS album_description,
alb.author AS album_author,
alb.path AS album_path,
alb.image AS album_image,
ali.path AS image_path
FROM album AS alb
LEFT JOIN albumconnect AS alc ON alc.albumid = alb.id
LEFT JOIN albumimages AS ali ON ali.id = alc.imageid
WHERE alb.id = '$realestAlbumID'";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
$albumPath = $row['album_path'];
$imagePath = $row['image_path'];
echo '<div class="imageContainerAlbums">';
echo '<li class="listAlbums">';
echo '<img class="specificAlbumThumnails" src="' . $albumPath . $imagePath . '" alt="Random image" />';
echo '</li>';
echo '</div>';
}
EDIT 1:
The columns from the sql statement which you don't use later are optional. So, you don't need to select all columns if you don't need them later.
It maybe that you are also becoming rows with NULL values for alc or ali tables. It means that not all albums have images. Then you must give us values you have in the tables, so that we can provide you the proper further WHERE conditions like WHERE ali IS NOT NULL. This answer of me is just the starting point for you.
EDIT 2:
This version is ok too. I just changed the sql statement.
<?php
$albumID = $_SERVER['QUERY_STRING'];
$realAlbumID = substr($albumID, 1);
$realestAlbumID = str_replace('%20', ' ', $realAlbumID);
$sql = "SELECT
alb.name AS album_name,
alb.description AS album_description,
alb.author AS album_author,
alb.path AS album_path,
alb.image AS album_image,
ali.path AS image_path
FROM albumimages AS ali
LEFT JOIN albumconnect AS alc ON alc.imageid = ali.id
LEFT JOIN album AS alb ON alb.id = alc.albumid
WHERE alb.id = '$realestAlbumID'";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
$albumPath = $row['album_path'];
$imagePath = $row['image_path'];
echo '<div class="imageContainerAlbums">';
echo '<li class="listAlbums">';
echo '<img class="specificAlbumThumnails" src="' . $albumPath . $imagePath . '" alt="Random image" />';
echo '</li>';
echo '</div>';
}

Related

Joining two tables based off a condition SQL

I am building an android app that uses geo location. I am trying to improve my overall app to improve its smoothness while running. I am using volly to connect to a php page on my web sever where the php page can then access my phpmyadmin database. My php page for updating locations is a horrible mess and I was hoping it can be fixed with the right sql query.
Lets get down to it.
So I have a table named users
and a table named friends
In this particular example david is friends with mark and jack. Also to clarify mark and jack are friends with david.
What I need to do is Write a query if given a user ID say for example 3 that will produce a table of that person and his friends ID, cordsV1, cordsV2 without any duplicate IDs in the table.
I was able to get this to work with using loops and variables ect but as I said it is a horrible mess.
Here is my current all sql query attempt:
SELECT DISTINCT ID, cordsV1, cordsV2 FROM `friends`,`users` WHERE user_one_ID = 1 AND status = 1;
HOWEVER this just returns all of the user IDs from the user table. I am really bad with sql so if someone could point me in the right direction it would be much appreciated.
Here is my horrible mess of code if you were wondering:
<?php error_reporting(E_ALL | E_STRICT); ?>
<?php
$THIS_USER_ID = $_GET['THIS_USER_ID'];
try {
$one = 1;
$db = new PDO("");
$sql = "SELECT * FROM friends WHERE user_one_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "' OR user_two_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "'";
$rows = $db->query($sql)
->fetchAll(PDO::FETCH_ASSOC);
$printMe = [];
foreach($rows as $row){
$printMe[] = $row;
}
$jsonArr = json_encode($printMe);
$characters = json_decode($jsonArr, true);
// Getting the size of the sample array
$size = sizeof($characters);
$neg = -1;
$sql2 = "SELECT * FROM users WHERE ID = '" . $neg . "'";
$sql3 = "";
$sql4 = "";
for ($x = 0; $x < $size; $x++ ){
if ($characters[$x]['user_one_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1){
$hold = $characters[$x]['user_two_ID'];
$sql3 = $sql3 . " OR ID = '" . $hold . "'";
} else if($characters[$x]['user_two_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1) {
$hold = $characters[$x]['user_one_ID'];
$sql4 = $sql4 . " OR ID = '" . $hold . "'";
}
}
$sql5 = $sql2 . $sql3 . $sql4;
$sql7 = "SELECT * FROM users WHERE ID = '" . $THIS_USER_ID . "'";
$printMe2 = [];
$rows3 = $db->query($sql7)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows3 as $row3){
$printMe2[] = $row3;
}
$rows2 = $db->query($sql5)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows2 as $row2){
$printMe2[] = $row2;
}
$jsonArr2 = json_encode($printMe2);
echo $jsonArr2;
$db = null;
} catch(PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>
Get the user-data
SELECT
*
FROM
users
WHERE ID = ?
Get the user-data of friends
SELECT
users.*
FROM
friends
JOIN
users ON users.ID = friends.user_two_ID
WHERE
friends.user_one_ID = ?
Better use prepared statements, or your app wont be alive very long due to SQL-Injections.
You also want to have a look at meaningful names.

PHP displaying data from four tables in one query (ie: LEFT JOIN)

I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));

php/mysql How to display images in an online forum

I've asked this question before, but got no answers, so I'm asking it again but this time, I will be more specific.
I have an online forum which I created from scratch with php and mysql, I've implemented the image uploading part naming the image by the topic id, from the posts table, Now I'm having problems displaying the images by pulling the name and the extension from the image table and attaching it to the topic id to be displayed. Now this is the code snippet for displaying topics (viewtopic.php)
$sql = "
SELECT SQL_CALC_FOUND_ROWS p.id
, p.subject
, p.body
, p.date_posted
, p.date_updated
, u.name as author
, u.id as author_id
, u.signature as sig
, c.count as postcount
, p.forum_id as forum_id
, f.forum_moderator as 'mod'
, p.update_id
, u2.name as updated_by
FROM forum_forum f
JOIN forum_posts p
ON f.id = p.forum_id
JOIN forum_users u
ON u.id = p.author_id
LEFT
JOIN forum_users u2
ON u2.id = p.update_id
LEFT
JOIN forum_postcount c
ON u.id = c.user_id
WHERE $topicid IN (p.topic_id,p.id)
ORDER
BY p.topic_id
, p.date_posted
LIMIT $start,$limit;
";
$result = mysqli_query($sql, $conn)
or die(mysql_error() . "<br>" . $sql);
while ($row = mysqli_fecth_array($result) )
{
echo "<p>($body) . "</p>";
echo $sig;
}
Now after echo ($body) if I run this query;
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysql_fetch_array($result))
{
$image_name = $therow["name"] ;
$ext = $therow["extension"];
}
?>
<img src="images/<?php echo $image_name.$ext; ?>" >
Help me, how do i get images to be displayed?
Try replace this:
while ($row = mysqli_fecth_array($result) )
{
echo "<p>($body) . "</p>";
echo $sig;
}
to
while ($row = mysqli_fetch_array($result) )
{
echo "<p>($body)" . "</p>";
echo $sig;
}
and this
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysql_fetch_array($result))
{
$image_name = $therow["name"] ;
$ext = $therow["extension"];
}
?>
to
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysqli_fetch_array($result))
{
$image_name = $therow["name"];
$ext = $therow["extension"];
}
?>

Echo data from mysql base to page

I have this query:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
placement.name AS placement,
advertiser.name AS advertiser,
country.name AS country
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
JOIN placement ON ads.placementId = placement.id
JOIN advertiser ON ads.advertiserId = advertiser.id
JOIN country ON ads.countryId = country.id
WHERE advertiserId = '$advertiser_id'";
and ads table
ads Table
ad_id PK
size
price
trafficsourceId FK
placementId FK
advertiserId FK
countryId FK
For getting data I'm using
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
}
I cant figure out how I need to print page so that it's not looking like rows but also need id's of for example trafficsource name. I want to make something like that:
EDITED:
<div id="adscontent">
<h1>Advertiser:</h1> Advertiser name
<h2>Traffic Sources:</h2> Company1, Company2, Company 3
<h2>Placements:</h2> Like: Newspaper, radio, website, bla bla
</div>
Thanks
You will need to play around with the printout but I think something like this will work:
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[$row['advertiser']]['countries'][] = $row['country'];
$results[$row['advertiser']]['trafficsources'][] = $row['trafficsource'];
$results[$row['advertiser']]['placements'][] = $row['placement'];
}
// And now print the data
foreach ($results as $arvertiser => $data)
{
echo "<h1>{$advertiser}</h1>";
// Print Placements
echo "Placements: " . implode(", ", $data['placements']) . '<br />;
// Print Countries
echo "Countries: " . implode(", ", $data['countries']) . '<br />;
// Print Placements
echo "Traffic Sources: " . implode(", ", $data['trafficsources']) . '<br />;
}
EDIT: If you need to add the IDs you will need to change your select to:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
trafficsource.id AS trafficsourse_id,
placement.name AS placement,
placement.id AS placement_id,
advertiser.name AS advertiser,
advertiser.id AS advertiser_id,
country.name AS country
country.id AS country_id
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
JOIN placement ON ads.placementId = placement.id
JOIN advertiser ON ads.advertiserId = advertiser.id
JOIN country ON ads.countryId = country.id
WHERE advertiserId = '$advertiser_id'";
From then on you can include this information in the $results array like so:
$results[$row['advertiser']['countries'] = array(
'id' => $row['country_id'],
'value' => $row['country')
);
and print out whatever you need from there.

SQL statement updates only one user's data

<?php
function get_user_id($username) {
return mysql_result(mysql_query("Select id From users Where username = '" . mysql_real_escape_string($username) . "'"), 0);
}
$sql = "select * from rating
WHERE user_id=" . get_user_id($myusername) . "
ORDER BY punkte ASC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$catid = $row['rating_id'];
$catname = $row['song_id'];
echo "<li id='item_$catid' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>$catname</li>";
}
?>
UPDATE:
Sorry, I found the mistake, it was quite stupid:
$catid = $row['rating_id'];
$catname = $row['song_id'];
It should be:
$catid = $row['song_id'];
$catname = $row['song_name'];
So, thanks to all! As always: You can't figure it out before you post a question to Stackoverflow :)
For your new question, you can solve it with a inner join:
select s.song_name from rating r
inner join songs s on s.song_name_id = r.song_id
Inner join
http://www.w3schools.com/sql/sql_join_inner.asp
Yes,
$catid = $row['rating_id']; //rating id is not related to song
TO
$catid = $row['song_id'];
$catname = $row['song_name'];

Categories