SQL Error when trying to JOIN tables - php

I'm trying to run this query:
$query = $conn->query("SELECT * FROM $table
LEFT JOIN vacatures ON bedrijven.id = vacatures.id
WHERE id = '$id'
AND bedrijfID = '$bedrijf_id'");
But it fails for some reason. I get this error.
Syntax error or access violation: 1066 Not unique table/alias
When I leave the JOIN part, the query is succesful. Why is this happening?
I'm using PHP & PDO to fetch the queries.
Thanks.
EDIT: I wrote the query thanks of the answers given. This is working:
$query = $conn->query("SELECT * FROM bedrijven
LEFT JOIN vacatures v ON bedrijven.id = v.bedrijfID WHERE v.bedrijfID = $bedrijf_id AND v.id = $id");

You need to specify one table or the other in WHERE id = '$id', even though they're equal to each other in this case.
You also need to make sure your LEFT JOIN includes $table:
$query = $conn->query("SELECT * FROM $table
LEFT JOIN vacatures ON $table.id = vacatures.id
WHERE $table.id = '$id'
AND bedrijfID = '$bedrijf_id'");
or:
$query = $conn->query("SELECT * FROM bedrijven
LEFT JOIN vacatures ON bedrijven.id = vacatures.id
WHERE bedrijven.id = '$id'
AND bedrijfID = '$bedrijf_id'");

Your question isn't super clear, but if you're just trying to do a simple join where the id on table 1 = id on table 2, then the below statement would work. If that's what you're attempting to do, then the AND statement is redundant. Hard to know what you're going for without a clearly defined question with clearly defined variables. Also, use prepared statements as shown below rather than inserting variables directly into your statement. And avoid SELECT * whenever possible. Only select what is absolutely necessary.
$query = $conn->prepare("SELECT * FROM bedrijven b
LEFT JOIN vacatures v
ON b.id = v.id
WHERE v.id = :id");
$query->bindValue(':id', $id);
$query->execute();

The '$id' will be treated as string not as variable.and you need to specify the id as table.id if both of the tables have a field called id.
$query = $conn->query("SELECT * FROM $table LEFT JOIN vacatures ON bedrijven.id = vacatures.id WHERE $table.id = $id AND bedrijfID = $bedrijf_id");

Related

Get userID from database

I have a simple blog where I'm practicing some php and mysql. I'm trying to display the username of the post author (you know where it says posted by Author).
I have two tables blog_members and blog_posts which are related 1 to many so I got a memberID field into the blog_posts. I'm trying to get the username of the member who's the author of the post.
I was thinking to do a join or something but I can't figure this out.
Here's what I was trying to do but it's not working because I'm sure I'm not using it properly.
$query1 = "SELECT username from blog_members JOIN blog_posts ON memberID = memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
PS: I got it working one way by using SESSION to get the userID but that works only if the user is logged is which is not the case, I want to display the name in any case.
Thanks!
Use inner join this way
And with a proper sanitize use $your_user_id for match
$query1 = "SELECT username
from blog_members
INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID
WHERE blog_posts.memberID = '" .$your_user_id . "';";
JOIN syntax is wrong in your query.
Use following query:
$query1 = "SELECT username from blog_members JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
Try something like this, usng INNER JOIN :
$query1 = "SELECT blog_members.username FROM blog_members INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
reference : http://www.w3schools.com/sql/sql_join.asp
Here is a solution using a simple WHERE condition (same performance Explicit vs implicit SQL joins) :
SELECT a.username FROM blog_members a, blog_posts b WHERE a.memberID = b.memberID
But if you need more information about MySQL Join : https://www.sitepoint.com/understanding-sql-joins-mysql-database/
Hope this helps !

Use INNER JOIN / JOIN for multiple query

What I have at the moment is to match the case from law_case, as in the database scheme below.
My code:
$query1 = "SELECT * FROM law_case WHERE id =?";
$query1vals = array($_GET['id']);
$ids = $adb->selectRecords($query1, $query1vals, false);
$a = $ids['case_type_id'];
$b = $ids['funding_pref'];
#
$query2 = "SELECT type_name FROM case_type WHERE id =?";
$query2vals = array($a);
$ids1 = $adb->selectRecords($query2, $query2vals, false);
$d = $ids1['type_name'];
#
$query3 = "SELECT * FROM expertise WHERE expertise_desc =?";
$query3vals = array($d);
$ids2 = $adb->selectRecords($query3, $query3vals, false);
$c = $ids2['id'];
#
$query4 = "SELECT * FROM individual_expertise WHERE expertise_id =?";
$query4vals = array($c);
$ids3 = $adb->selectRecords($query4, $query4vals, false);
$e = $ids3['individual_id'];
#
$query5 = "SELECT * FROM individual WHERE id =?";
$query5vals = array($e);
$ids4 = $adb->selectRecords($query5, $query5vals, false);
$f = $ids4['network_member_id'];
#
$query6 = "SELECT * FROM network_member WHERE id =?";
$query6vals = array($f);
$ids5 = $adb->selectRecords($query6, $query6vals, false);
And what it does is it only gets one network_member.
I want to use INNER JOIN, JOIN or LEFT JOIN and use a while looking to get the different member_name and the URL for each network_member or who's individual has the same expertise_id from the individual_expertise table.
I'm new to JOIN and tried this code but it doesn't work:
$sql = "SELECT member_name, url
FROM individual_expertise
LEFT JOIN individual
USING (individual_id)
LEFT JOIN network_member
USING (network_member_id)
WHERE expertise_id = ?";
$ids3 = $adb->selectRecords($sql, $query4vals, false);
echo $ids3['member_name'];
You need to get an overview of JOIN types. You have to build a query using INNER, LEFT, RIGHT, FULL joins depending on your logical requirements. You can assume that INNER join is equal to && or AND operators in conditional statements, I mean records must match in both tables.
While, LEFT join will return all rows from left table of join and matched rows from right table of join. And RIGHT is inverse of LEFT.
And FULL join is an example of || or OR in operators in conditional statements. I mean either a match in both tables.
So you have to join depending on logic you require.
See here
Do you know the difference between INNER JOIN and LEFT JOIN? I think you don't. You need an INNER JOIN here.
I think this is the right solution for your question:
SELECT
network_member.member_name,
network_member.url
FROM
network_member
INNER JOIN
individual ON individual.network_member_id = network_member.id
INNER JOIN
individual_expertise ON individual_expertise.individual_id = individual.id
WHERE
individual_expertise.expertise_id = ?

Inner/Left join with two different where clauses

i'm in the process of joining two tables together under two different conditions. For primary example, lets say I have the following nested query:
$Query = $DB->prepare("SELECT ID, Name FROM modifications
WHERE TYPE =1 & WFAbility = '0'");
$Query->execute();
$Query->bind_result($Mod_ID,$Mod_Name);
and this query:
$Query= $DB->prepare("SELECT `ModID` from `wfabilities` WHERE `WFID`=?");
$Query->bind_param();
$Query->execute();
$Query->bind_result();
while ($Query->fetch()){ }
Basically, I want to select all the elements where type is equal to one and Ability is equal to 0, this is to be selected from the modifications table.
I further need to select all the IDs from wfabilities, but transform them into the names located in modifications where WFID is equal to the results from another query.
Here is my current semi-working code.
$Get_ID = $DB->prepare("SELECT ID FROM warframes WHERE Name=?");
$Get_ID->bind_param('s',$_GET['Frame']);
$Get_ID->execute();
$Get_ID->bind_result($FrameID);
$Get_ID->fetch();
$Get_ID->close();
echo $FrameID;
$WF_Abilties = $DB->prepare("SELECT ModID FROM `wfabilities` WHERE WFID=?");
$WF_Abilties->bind_param('i',$FrameID);
$WF_Abilties->execute();
$WF_Abilties->bind_result($ModID);
$Mod_IDArr = array();
while ($WF_Abilties->fetch()){
$Mod_IDArr[] = $ModID;
}
print_r($Mod_IDArr);
$Ability_Name = array();
foreach ($Mod_IDArr AS $AbilityMods){
$WF_AbName = $DB->prepare("SELECT `Name` FROM `modifications` WHERE ID=?");
$WF_AbName->bind_param('i',$AbilityMods);
$WF_AbName->execute();
$WF_AbName->bind_result($Mod_Name);
$WF_AbName->fetch();
$Ability_Name[] = $Mod_Name;
}
print_r($Ability_Name);
See below:
SELECT ModID,
ID,
Name
FROM modifications M
LEFT JOIN wfabilities WF
ON WF.ModID = M.ID
WHERE TYPE =1 & WFAbility = '0'
To do this, you need to join your tables, I'm not quite sure what you are trying to do so you might have to give me more info, but here is my guess.
SELECT ID, Name, ModID
FROM modifications
JOIN wfabilities
ON WFID = ID
WHERE TYPE = '1'
AND WFAbility = '0'
In this version I am connecting the tables when WFID is equal if ID. You will have to tell me exactly what is supposed to be hooking to what in your requirements.
To learn more about joins and what they do, check this page out: MySQL Join
Edit:
After looking at your larger structure, I can see that you can do this:
SELECT modifications.Name FROM modifications
JOIN wfabilities on wfabilities.ModID = modifications.ID
JOIN warframes on warframes.ID = wfabilities.WFID
WHERE warframes.Name = 'the name you want'
This query will get you an array of the ability_names from the warframes name.
This is the query:
"SELECT A.ID, A.Name,B.ModID,C.Name
FROM modifications as A
LEFT JOIN wfabilities as B ON A.ID = B.WFID
LEFT JOIN warframes as C ON C.ID = B.WFID
WHERE A.TYPE =1 AND A.WFAbility = '0' AND C.Name = ?"

joining two tables and fetching values from them error

i am joining the two tables but is giving me error that mysql_fetch_array() expects parameter 1 to be resource,
<?php
$result=mysql_query("SELECT * FROM `photo_gallery`.`photographs` WHERE id=1");
$result .=mysql_query("SELECT * FROM `photo_gallery`.`users` WHERE id=1");
while($row=mysql_fetch_array($result))
{
echo 'You are Welcome'.'<br/>';
$Id=$row['id'];
$Name=$row['username'];
$Batch=$row['password'];
$Address=$row['first_name'];
$Course=$row['last_name'];
$filename=$row['filename'];
$type=$row['type'];
echo 'your ID is'.$Id.'<br/>'.'username '. $Name.'<br/>'.'your password '. $Batch.'<br/>'.'yor first name'. $Address. '<br/>'.'last'.$Course.'<br/>'.'file name is'.'<br/>'.$filename.'<br/>'.'type is '.$type;
}
?>
Here is the most easy syntax to use join function
$query=mysql_query("SELECT * FROM `databasename`.`firstablename` JOIN `seconddatabasename` ON firsttablename.id = secondtablename.id ");
If you want to work with join array than visit this link http://www.w3schools.com/php/func_string_join.asp.
I hope you get what join function is used for.
Try this.
$query = "SELECT * FROM photographs INNER JOIN users ON photographs.id = users.id";
$result = mysql_query($query);
you cannot chain mysql queries in php that way. you have 2 options.
create a real mysql join.
you can use the shorthand syntax:
SELECT * FROM `photographs` p, `users` u WHERE p.id = u.id AND id=1
or a real join:
SELECT * FROM `photographs` p INNER JOIN `users` u WHERE p.id = u.id AND id=1
might i suggest reading more about mysql joins:
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

One query instead of two?

Here I'm making two queries with PHP. Is there something more simple? One query instead of two?
$id = mysql_real_escape_string($_GET["id"]);
$result = mysql_query("SELECT * FROM questionstable WHERE id=$id");
$row = mysql_fetch_assoc($result);
$category = $row['category'];
$main = mysql_query("SELECT name FROM categorytable WHERE id=$category");
SELECT questionstable.*, categorytable.name
FROM questionstable
INNER JOIN categorytable
ON categorytable.id = questionstable.category
WHERE questionstable.id=$id
As an aside, assuming your questionstable.id is numeric, you could use $id = (int)$_GET["id"] and save some writing. (It's also probably a safer bet. Just because it's escaped doesn't mean it's completely safe--especially when it's not within quotes [gives you a LOT of options for SQL injection]. ;-))
Please try:
SELECT name
FROM categorytable
WHERE id = (
SELECT category
FROM questionstable
WHERE id = $id
)
$id = mysql_real_escape_string($_GET["id"]);
$main = mysql_query("SELECT c.name FROM categorytable c inner join questionstable q on c.category = q.category WHERE q.id = $id");
Do not use inner join use left join instead, it won't return any result if the category is not found
SELECT questionstable.*, categorytable.name
FROM questionstable
LEFT JOIN categorytable
ON categorytable.id = questionstable.category
WHERE id=$id

Categories