Php query regarding 2 FK and 1 Primary Key - php

In my table internships, I have two foreign keys id_promoter_internship and id_supervisor_internship. In the table business_contacts I have 1 primary key id_business. I'm trying to get data from the business_contacts table which is linked to the internships table. Is the following query correct?
public function update_form_business_contact($name_enterprise){
$query = "
SELECT
*
FROM business_contacts
,internships
WHERE
business_contacts.id_business = internships.id_supervisor_internship
AND internships.name_enterprise_internship = '$name_enterprise'";
$result = $this->_db->query($query);
# Go through results of teachers
if($result->rowCount()!=0){
while($row=$result->fetch()){
$contact= new businesscontact ( $row->id_business,$row->firstname_business,$row->lastname_business,$row->service_business,$row->function_business,$row->phone_business,$row->phone_secretary_business,$row->mobile_business);
}
}
return $contact;
}
My question is: Does the primary key have to reference both foreign keys? If so how would I do that.
Thanks for your help.

You should rewrite the query using join like:
$query = "SELECT *
FROM business_contacts bc
INNER JOIN internships i ON bc.id_business = i.id_supervisor_internship
WHERE internships.name_enterprise_internship = '$name_enterprise'";

If you need both ids then left join twice using both ids:
$query = "select
*
from internships i
left join business_contacts bc ON bc.id_business = i.id_supervisor_internship
left join business_contacts bc2 on bc2.id_business = i.id_promoter_internship
WHERE
i.name_enterprise_internship = '$name_enterprise'";
If you need only supervisor id:
$query = "select
*
from internships i
left join business_contacts bc ON bc.id_business = i.id_supervisor_internship
WHERE
i.name_enterprise_internship = '$name_enterprise'";
If you need only promoter id:
$query = "select
*
from internships i
left join business_contacts bc on bc.id_business = i.id_promoter_internship
WHERE
i.name_enterprise_internship = '$name_enterprise'";
To get use specific parameter in the join:
$query = "select
*
from internships i
left join business_contacts bc ON bc.id_business = i.id_promoter_internship and i.name_enterprise_internship = '$name_enterprise'";

Related

How to display data from database table independently

Problem desc.
I have databese called demo. In this databse i have columns. Two of them are otk and zamestnanci.
/*zamestnanci = employees*/
So i have some data in otk table:
/*otk columns: id_otk|ciarovy_kod|cislo_zakazky|zamestnanci|*/
/*id_otk = autoincrement*/
/*zamestnanci can be only number*/
INSERT INTO otk (ciarovy_kod, cislo_zakazky, zamestnanci) VALUES ('65464', '564', '1');
And now i have some data in zamestnanci:
/*zamestnanci columns: id_zamestnanci|titul|meno|titulz|*/
/*id_zamestnanci = autoincrement*/
INSERT INTO zamestnanci (titul, meno, titulz) VALUES ('ads', 'John', 'das');
And now here is my code for displaing and searching data from otk:
if(isset($_GET['hladat']))
{
$hladatHodnotu = $_GET['hladatHodnotu'];
// hladat v setkych stlpcoch
// pouzitie concat funkcie pre vyhladanie iba urciteho stlpca
$sql = "SELECT * FROM otk JOIN zamestnanci ON zamestnanci.id_zamestnanci=otk.zamestnanci
JOIN zariadenia ON zariadenia.id=otk.zariadenie
JOIN stav ON stav.id=otk.stav
JOIN technologie ON technologie.id=otk.technologie
JOIN obrazky ON obrazky.id_obrazky=otk.obrazok
WHERE CONCAT(`ciarovy_kod`) LIKE '%".$hladatHodnotu."%'";
$vysledokHladania = filtrovatTabulku($sql);
}
//Zobrazovanie dat z viacerych tabuliek do jednej
/* JOIN zamestnanci ON zamestnanci.id_zamestnanci=otk.zamestnanci
JOIN zariadenia ON zariadenia.id=otk.zariadenie
JOIN stav ON stav.id=otk.stav
JOIN technologie ON technologie.id=otk.technologie
JOIN obrazky ON obrazky.id_obrazky=otk.obrazok*/
else {
$sql = "SELECT * FROM otk JOIN zamestnanci ON zamestnanci.id_zamestnanci=otk.zamestnanci
JOIN zariadenia ON zariadenia.id=otk.zariadenie
JOIN stav ON stav.id=otk.stav
JOIN technologie ON technologie.id=otk.technologie
JOIN obrazky ON obrazky.id_obrazky=otk.obrazok";
//$sql = "SELECT * FROM zariadenia, otk WHERE zariadenia.id=otk.zariadenie";
$vysledokHladania = filtrovatTabulku($sql);
}
// funkcia na pripojenie a spustenie $sql
function filtrovatTabulku($sql)
{
//Zahrnut pripojenie k db
include'../db/dbinfo.php';
$vysledokHladania = mysqli_query($con, $sql);
return $vysledokHladania;
}
And now when i empty table "zamestnanci" it will not display data from "otk" with id of that "zamestnanci" because he do not exist. So i want to ask you if there is way how to display if "zamestnanci" is not exist.
You're using the wrong JOIN.
You should learn how each join works before using them, read more about them here http://www.sql-join.com/sql-join-types/

Select and unlink file on 3 tables

Please help me to check my query. I have search a lot and I have'nt try to select 3 tables before.
I think I got it right but I dont know why there's nothing happen.
public function delSection($delete_id)
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_section
JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:del_id");
$stmt->execute(array(":del_id"=>$delete_id));
while($linkRow=$stmt->fetch(PDO::FETCH_ASSOC))
{
unlink(__DIR__."/Admin/cover_images/".$linkRow['sec_cover']);
unlink(__DIR__."/Admin/Files/".$linkRow['sec_id']."/".$linkRow['file_name']);
rmdir(__DIR__."/Admin/Files/".$linkRow['sec_id']);
}
$stmt2 = $this->conn->prepare("DELETE tbl_section, tbl_login, tbl_content FROM tbl_section
JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:del_id");
$stmt2->bindparam(":del_id",$delete_id);
$stmt2->execute();
return true;
}
What I am trying to do is to select * from 3 tables and fetch their data with fk sec_id
here's the manual running of query
link:
Code:
Done With LEFT OUTER JOIN QUERY
$stmt = $this->conn->prepare("SELECT * FROM tbl_section
LEFT OUTER JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
LEFT OUTER JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:unlink_id");

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 = ?

SQL Error when trying to JOIN tables

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");

Mysql Join two Id's to get there Usernames

Im trying to get in Array that contains the results from a MYSQL query.
I have 2 ids stored in the table hitlist user_id and mark_id
they need to join in the table users to retrieve there usernames that match there id's and in the future other variables.
i have this working in a weird way and was hopeing to get this working in a more efficent simple way similar to this
$Hitlists = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id AND hitlist.mark_id = users.id")->fetchAll();
This is the code i have that is working...for now it looks like it might give me problems later on.
<?php
$index = 0;
$Hitlists = array();
$st = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id")->fetchAll();
$sth = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.mark_id = users.id")->fetchAll();
foreach($st as $id)
{
$Hitlists[] = $id;
}
foreach($sth as $id)
{
$Hitlists[$index]['markedby'] = $id['username'];
$Hitlists[$index]['mark_id'] = $id['mark_id'];
$index++;
}
The way you are joining the table is wrong. You can get the exact records you want, you need to join users table twice to get the username of each ID
SELECT a.*,
b.username User_name,
c.username mark_name
FROM hitlist a
INNER JOIN users b
ON a.user_id = b.id
INNER JOIN users c
ON a.mark_id = c.id
and you can access
$result['User_name']
$result['mark_name']

Categories