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/
Related
I develop a chat system where students and staff can exchange different messages. I have developed a database where we have five tables: the staff table, the student, the message and two mapping tables the staff_message and stu_message. These tables contain only the student/staff id and the message id.
My problem is that I cannot order the messages. I mean that I cannot figure out how can I make one SQL statement that will return all messages and be ordered by for example the ID. The code that I have made is this:
$qu = mysqli_query($con,"SELECT * FROM stu_message");
while($row7 = mysqli_fetch_assoc($qu)){
$que = mysqli_query($con, "SELECT * FROM student WHERE studentid =".$row7['stu_id']);
while($row8 = mysqli_fetch_assoc($que)) {
$username = $row8['username'];
}
$query3 = mysqli_query($con, "SELECT * FROM message WHERE id=".$row7['mid']);
while($row6 = mysqli_fetch_assoc($query3)) {
echo $row6['date']."<strong> ".$username."</strong> ".$row6['text']."<br>";
}
}
$query2 = mysqli_query($con, "SELECT * FROM staff_message");
while($row3 = mysqli_fetch_assoc($query2)){
$query = mysqli_query($con, "SELECT * FROM staff WHERE id =".$row3['staff_id']);
while($row5 = mysqli_fetch_assoc($query)) {
$username = $row5['username'];
}
$query3 = mysqli_query($con, "SELECT * FROM message WHERE id=".$row3['m_id']);
while($row6 = mysqli_fetch_assoc($query3)) {
echo $row6['date']."<strong> ".$username."</strong> ".$row6['text']."<br>";
}
}
?>
The result is different from that I want. To be more specific first are shown the messages from the students and then from the staff. My question is, is there any query that it can combine basically all these four tables in one and all messages will be shown in correct order? for example by the id?
Thank you in advance!
First, use JOIN to get the username corresponding to the stu_id or staff_id, and the text of the message, rather than separate queries.
Then use UNION to combine both queries into a single query, which you can then order with ORDER BY.
SELECT u.id, u.text, u.username
FROM (
SELECT s.username, m.text, m.id
FROM message AS m
JOIN stu_message AS sm ON m.id = sm.mid
JOIN student AS s ON s.id = sm.stu_id
UNION ALL
SELECT s.username, m.text, m.id
FROM message AS m
JOIN staff_message AS sm ON m.id = sm.m_id
JOIN staff AS s ON s.id = sm.staff_id
) AS u
ORDER BY u.id
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");
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'";
I am creating a dashboard to keep me updated on call agent status.an agent will have multiple records in the log. I need to pull the most recent status from the agent log. The only way I have found is to query the agent table to pull the agents with status changes made today and then query the agent log table to pull the most recent status.
is there a way to combine the two queries.? Here are my queries
$sql_get_agents = "SELECT id FROM agent WHERE lastchange LIKE '{$today}%'";
if($dta = mysql_query($sql_get_agents)){
while($agent = mysql_fetch_assoc($dta)){
$curr_agent[] = $agent;
}
foreach($curr_agent as $agents_online){
$get_status_sql = "SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
INNER JOIN agent a ON al.agentid = a.id
INNER JOIN agent_status s ON a.agent_statusid = s.id
WHERE al.agentid = '{$agents_online['id']}'";
if($dta2 = mysql_query($get_status_sql)){
while($agent_status = mysql_fetch_assoc($dta2)){
$curr_status[] = $agent_status;
}
}
}//end for each
return $curr_status;
}//end if
Why don't you join the 2 queries into one adding the WHERE lastchange LIKE '{$today}%' condition in the second query?
Using the IN clause should work :
"SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
INNER JOIN agent a ON al.agentid = a.id
INNER JOIN agent_status s ON a.agent_statusid = s.id
WHERE al.agentid IN (SELECT id FROM agent WHERE lastchange LIKE '{$today}%');
You were close with what you have. This will get rid of the need to do both queries, or query in a loop.
edit: adding example code to loop over the results as well.
edit2: changed query.
$query = "SELECT
a.firstname,
a.lastname,
al.agentid,
al.agent_statusid,
s.id as statusid,
s.status,
MAX(al.datetime) as datetime
FROM agent a
LEFT JOIN agent_log al ON al.agentid = a.id
LEFT JOIN agent_status s ON a.agent_statusid = s.id
WHERE a.lastchange LIKE '{$today}%'";
$status = array();
$results = mysql_query( $query );
while( $agent = mysql_fetch_assoc( $results ) )
$status[] = $agent;
print_r( $status );
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']