Mysql select from two tables join - php

i have two tables "employees" and "dependents",
Employees
|employee_No| Employee_name |
|1558 | Bean |
|1557 | Juliet |
|1556 | Zeke |
Dependents
|employee_No| dependent_name | relationship|
|1558 | Kelvin | Son |
|1558 | Mary | Daughter |
|1556 | Janet | Spouse |
is there a way i could get this data in one MySQL statement and display using php i.e. loop employees and dependent under that employee then move to the next employee.
current php code is
$employees = select_all_employees()
foreach ($employees as $covered){
echo $covered['Employee_name'].'<br/>';
$get_dependent = $select_dependent($covered["employee_No "]);
if($get_dependent != 0){
foreach($get_dependent as $details){
echo $details['dependent_name '].' '.$details['relationship'].'<br/>';
}
}
}
this takes too much time to load when there are thousand employees and dependents
expected outcome
|employee_No| dependent_name | relationship|
--------------------------------------------
|1558 | Bean | principal |
|1558 | Kelvin | Son |
|1558 | Mary | Daughter |
|1557 | Juliet | principal |
|1556 | Zeke | principal |
|1556 | Janet | Spouse |

The easiest way to get the results you want is with a UNION of the rows of the Employees table with the JOIN of the Employees with their Dependents. We do this UNION as a derived table so that we can then order the results by employee_No and also place the principal first for each employee_No. By doing it this way your PHP code becomes a simple loop over all the results.
SELECT employee_No, Employee_name AS dependent_name, 'principal' AS relationship
FROM Employees
UNION ALL
SELECT e.employee_No, d.dependent_name, d.relationship
FROM Employees e
JOIN Dependents d on d.employee_No = e.employee_No
ORDER BY employee_No DESC, relationship = 'principal' DESC
Output:
employee_No dependent_name relationship
1558 Bean principal
1558 Mary Daughter
1558 Kelvin Son
1557 Juliet principal
1556 Zeke principal
1556 Janet Spouse
Demo on dbfiddle

How about this query:
SELECT a.*, "principal" as 'relationship' FROM Employees a
UNION SELECT b.* FROM Dependents b ORDER BY employee_no DESC
DBFIDDLE here

You can use join or Map the columns. Check the index in both the tables for your slowness of query. Index should be employee_No in both the tables. And then loop your query output.
<?php
$qryOutput = array();
$query = "SELECT A.*, B.* FROM Employees A LEFT JOIN Dependents B ON A.employee_No=B.employee_No" // query
$qryOutput = execute_Query($query); // Check this syntax. For Execute query
// Loop through your Query Output
foreach ($qryOutput as $key => $value)
{ echo $value["employee_No"]." ".$value["dependent_name"]." ".$value["relationship"]; }
?>

You can use either INNER JOIN or LEFT JOIN to actualize it.
Try something like this. Though I have not tested the code.
Your table need to be created with foreign key references for it to work. see sample below. I have tested it.
create table Employees(employee_No int primary key,Employee_name varchar(100));
create table Dependents(employee_No int primary key,dependent_name varchar(100), relationship varchar(100)
foreign key (employee_No) references Employees(employee_No));
Insert for testing
insert into Employees(employee_No,Employee_name) values(1558,'Bean');
insert into Employees(employee_No,Employee_name) values(1557,'Juliet');
insert into Dependents(employee_No,dependent_name,relationship) values(1558,'kevin','son');
code
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$query = 'SELECT Employees.employee_No, Employees.Employee_name, Dependents.employee_No, Dependents.dependent_name,
Dependents.relationship FROM Employees
LEFT JOIN Dependents ON Employees.employee_No = Dependents.employee_No
ORDER BY Employees.Employee_name';
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
$empno = $row['employee_No'];
$empname = $row['Employee_name'];
$relation = $row['relationship'];
$dependant_name = $row['dependent_name'];
//you can now echo
echo $dependant_name.' '.$relation.'<br/>';
}
?>

Related

Problems joining two tables properly

I have these two tables above. The first table contains different drugs. The second table contains verified combinations of any two drugs from the first table.
By default there is a reference drug where drugID = $_GET['ref'] in the URL. Lets just say default.php?ref=3 for vaccine.
I want to list all drugs from the drugs table, except where drugID = $_GET['ref'] = 3. This will show all drugs except vaccine. This is done like this:
$ref = htmlspecialchars($_GET['ref']);
$sql = "SELECT * FROM drugs WHERE drugID != {$ref} ORDER BY drug ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["drug"];
}
}
For every drug in the loop (drugID) I want to check whether there exist a comboID where drugID and $_GET['ref'] are both found in either drug1_ID or drug2_ID. If such a comboID exist, echo "combination found:" . row['comboID'] . row["interaction"]. This should return 4 combinations with vaccine.
I have tried left, right, inner and full join of the tables, but nothing seems to work. How can this be done?
In the following example, I tried to left join:
SELECT *
FROM drugs
LEFT JOIN combination
ON (drugs.ID = combination.drug1_ID AND {$ref} = combination.drug2_ID) OR ({$ref} = combination.drug1_ID AND drugs.ID = combination.drug2_ID);
This just returns every drug, but more than once if combination is found.
Assumptions
You want to SELECT all drugs from the drugs table except for the reference drug
You want to join the combination table so as to show combinations of drugs with the reference drug.
Output should look something like:
drugs.drugID | drugs.drug | combination.comboID | combination.interaction
-------------+-----------------+---------------------+-------------------------
1 | Paracetamol | 1 | ok
2 | Benzodiazepine | 2 | ok
4 | Calcium blocker | 3 | ok
5 | Sodium blocker | 4 | ok
6 | Cold meds | NULL | NULL
7 | Pain meds | NULL | NULL
8 | Grape juice | NULL | NULL
9 | Cannabis | NULL | NULL
10 | Salt | NULL | NULL
SQL Query
SELECT drugs.drugID, drugs.drug, combination.comboID, combination.interaction
FROM drugs
LEFT JOIN combination -- Left join so we select all rows from FIRST table
ON drugs.drugID IN (combination.drug1_ID, combination.drug2_ID) -- Only join where drug from first table is one of the drugs in the combination
AND ? IN (combination.drug1_ID, combination.drug2_ID) -- Only join where the reference drug is also in the combination
WHERE drugs.drugID != ? -- Exclude reference drug from first table
PHP - mysqli
$reference_drug = $_GET["ref"] ?? NULL;
if($reference_drug){
$sql = "
SELECT drugs.drugID, drugs.drug, combination.comboID, combination.interaction
FROM drugs
LEFT JOIN combination
ON drugs.drugID IN (combination.drug1_ID, combination.drug2_ID)
AND ? IN (combination.drug1_ID, combination.drug2_ID)
WHERE drugs.drugID != ?
";
$query = $conn->prepare($sql);
$query->bind_param("ii", $reference_drug, $reference_drug);
$query->execute();
$query->store_result();
$query->bind_result($drug_id, $drug_name, $combination_id, $combination_status);
while($query->fetch()){
echo "$drug_id, $drug_name, $combination_id, $combination_status\n";
}
}
else{
echo "Error: No reference drug supplied.";
}
PHP - PDO
Don't forget that any user input should be treated as untrusted_ and therefore shouldn't be put directly into a query.
$db_host = "127.0.0.1";
$db_user = "some_user";
$db_pass = "db_password";
$db_name = "db_name";
$this->pdo = new pdo(
"mysql:host={$db_host};dbname={$db_name}",
$db_user,
$db_pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
$reference_drug = $_GET["ref"] ?? NULL;
if($reference_drug){
$sql = "
SELECT drugs.drugID, drugs.drug, combination.comboID, combination.interaction
FROM drugs
LEFT JOIN combination
ON drugs.drugID IN (combination.drug1_ID, combination.drug2_ID)
AND ? IN (combination.drug1_ID, combination.drug2_ID)
WHERE drugs.drugID != ?
";
$query = $pdo->prepare($sql);
$query->execute([$reference_drug, $reference_drug]);
while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row["drugID"];
}
}
else{
echo "Error: No reference drug supplied.";
}

Get ID from one tabe and find name for that ID

In my data base I have 3 tables.
user (table name)
so many row are there one of the row name user and if
--------------------
| id | user |
--------------------
| 7 | user |
| 8 | user_name_2 |
| 11 | user_name_5 |
--------------------
and another table call data
----------------------------
| id | user-id | number |
----------------------------
| 1 | 7 | 789654125 |
| 2 | 8 | 465654545 |
| 3 | 11 | 884554511 |
----------------------------
In table td user_id is table user id
now I want to show name and number in php
$conn = mysqli_connect("localhost","root","QAZWS12","user");
$sql = "SELECT * FROM user"
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
}
did the same and get $number = $row["number"]
Now I want is in data table user id auto get table user number how can i do that?
Final output
user 789654125
user_name_2 465654545 like that
You have to use join here. For more details on different types JOINS refer either official MySQL doc or search online
replace this query
$sql = "SELECT u.id,u.user AS user_name,d.number AS user_number
FROM user u LEFT JOIN description d ON u.id = d.user-id";
The above query will fetch user id and username and user number
replace this too
$id = $row["id"].' '.$row['user_name'].' '.$row['user_number'].'<br/>';
This outputs as
7 user 789654125
Try below SQL query with LEFT JOIN to get the username with their mobile number in the result set:
$sql = "SELECT u.user, d.number
FROM user as u
LEFT JOIN data as d ON d.user-id = u.id
"
user SQL Left join
$sql = "SELECT * FROM user LEFT JOIN call_data ON user.id = call_data.user-id";
while accessing data
$number = $row['number'];
learn about SQL JOINS TUTORIAL

Retrieve Fields from Foreign key table

I have these two tables and I want to get some values from the second table for two foreign key in the first table.
Team table:
ID | Name | No_Players | Country | F_Year | Team_Logo
-----+---------------+------------+----------+--------+----------------------
1 | Real Madrid | 22 | Spain | 1940 | Http://Xyz.jpg
2 | Arsenal | 22 | England | 1950 | Http://XXYYZZ.jpg
3 | FCB.Barcelona | 22 | Spain | 1960 | Http://YYZZz.jpg
4 | Bayern Meunekh| 22 | Germany | 1940 | Http://GGG.jpg
Matches table:
ID | Date |First_Team | Second_Team | M_Country |M_City | M_Period | Result
------------------------------------------------------------------------------------------
1 |15-02-2016 | Real Madrid | Arsenal | Spain | Madrid | 120 | 1-1
2 |19-03-2016 | FCB.Barecolna | Madrid | Spain | Madrid | 90 | 4-5
And I want to Get the Team_Logo For each team in the matches table in the json form in this PHP Script. I've tried to get teams logo but unfortunately the query is invalid.
If anyone can help me please?
<?php
require ('config.php');
$conn = mysqli_connect($servername, $username, $password, $db);
$query = "select * from matches,team where matches.first_team=team.Name OR matches.second_team=team.Name";
$result = mysqli_query($conn, $query);
$rows = array();
echo mysqli_error($conn);
while($row = mysqli_fetch_assoc($result)) {
$rows[]=$row;
}
echo json_encode($rows);
?>
SELECT
matches.*,
t1.Team_Logo AS logo1,
t2.Team_Logo AS logo2
FROM matches
JOIN team AS t1
ON t1.Name = matches.First_Team
JOIN team As t2
ON t2.Name = matches.Second_Team
Also note that you should not select * because the Id columns from the team tables will override the Id column of the matches table.
That's why you should include only columns you like to select.
You should try this query :
$query="select m.*,t.* from matches as m INNER JOIN on team as t1 ON m.First_Team=t1.Name JOIN team As t2
ON m.Second_Team=t2.Name";
Use relational database structure.
add primary key for both table
add reference key of first table's primary key in second table as foreign key.
and refer bellow query.
sql="SELECT * FROM Matches as m JOIN Team as t ON t.ID = m.t_id where t.id=1 OR t.id=2

PHP SQL Query That Displays Certain Results Based On Values In Another Table

Right now, I have two database tables. Table history_2014 has a column(member) that says whether or not a member is active (Y or N). I have another table called history_overall that contains all of the contact information for these members. I need a table that will only show the rows of history_overall for active members. Right now, I have this PHP:
<?php
$con=mysqli_connect("localhost","myusername","mypassword","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM history_overall");
echo "<table border='1'>
<tr>
<th>Address 1</th>
<th>Last Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['address1'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The current code will allow me to display all rows, but I need to be able to display certain rows based on the other table.
what column ties the two tables together?
A JOIN will accomplish this if there is a relationship.
Example:
SELECT history_overall.* FROM members
JOIN history_overall
ON history_overall.member_id = members.id
WHERE members.active = 'Y';
----Edit/Comment----
Since I'm not able to add the table structure layout in a comment I will comment here.
It is more valuable when wanting to retrieve specific records from the database to provide us with the table schema as opposed to the actual table names. As well as an example of the resulting data you want as a result.
All you really provided to us with is table history_2014 with columns (member = Y|N), table history_overall with columns (address1, last_name) which doesn't allow us to build a relationship between the two (or more) tables.
Here is an example assuming both tables have a memberid column:
----------------------- -------------------------------------
| table1 | | table2 |
----------------------- -------------------------------------
| member | memberid | | address1 | full_name | memberid |
----------------------- -------------------------------------
| Y | 1 | | 123 street | jon doe | 1 |
----------------------- -------------------------------------
| N | 2 | | 789 court | jane doe | 2 |
----------------------- -------------------------------------
| Y | 3 | | 456 road | foo bar | 3 |
----------------------- -------------------------------------
Question: How can I retrieve records from table2 where the member in table1 is 'Y'?
This is my desired result of the records:
-------------------------------------
| recordset |
-------------------------------------
| address1 | full_name | memberid |
-------------------------------------
| 123 street | jon doe | 1 |
-------------------------------------
| 456 road | foo bar | 3 |
-------------------------------------
Answer query:
SELECT table2.*
FROM table1
JOIN table2
ON table1.memberid = table2.memberid
WHERE table1.member = 'Y'
Explained:
Retrieve all columns in table2 that the memberid column in table1 is the same as the memberid column in table2 from the rows in table1 that the member column contains Y as a value with no ordering or limit on the amount of records returned.
I guess you have some kind of Id of the user in both tables, you could make a query creating a join between the two tables where id matches and selecting only the rows where member = 'Y'
Simply use this method
select * from history_overall,members where members.status='active'
You will get all the active members results including history also.
Use a table join (MySQL doc: http://dev.mysql.com/doc/refman/5.7/en/join.html).
In short, something like:
SELECT ho.*
FROM history_overall AS ho
RIGHT JOIN history_2014 AS h ON ho.memberId = h.memberId
WHERE h.isActive = 'Y';
Obviously your field names are probably different...

Matching and returning rows in php and MySQL

I would love to get some help with this. I'm using php and MySQL to build a website. I currently have 3 tables, I'll include less in the examples. Basically I have a users table, a groups table and a grouplink table. What I have is the uid from the users table.
How should I go about it in php so I could, let's say: match users-uid to grouplink-uid, get the grouplink-gid it matches with, match grouplink-gid to groups-gid and return groups-grpname? And goes on a while loop so all group names the user is associated with are displayed.
Thanks in advance to those who will be willing to extend a hand.
users
-------
| uid |
-------
| 1 |
-------
groups
---------------
| gid |grpname|
---------------
| 1 | grp1 |
---------------
| 2 | grp2 |
---------------
grouplink
-------------------
| glid| uid | gid |
-------------------
| 1 | 1 | 1 |
-------------------
| 2 | 1 | 2 |
-------------------
uid is fk to uid in users while gid is fk to gid in groups
That's just a simple 2-way join query:
SELECT users.uid, groups.gid, groups.grpname
FROM users
INNER JOIN grouplink ON users.uid = grouplink.uid
INNER JOIN groups ON grouplink.gid = groups.gid
the actual retrieval of a joined query result is no different than a single table query - you've just got more fields to deal with.
The SQL query that will get you what you're looking for goes something like this (assuming no null values in the grouplink table):
SELECT u.uid, g.gid, g.grpname
FROM users u
JOIN grouplink gl ON u.uid = gl.uid
JOIN groups g ON gl.gid = g.gid
Here is one way:
SELECT users.uid, groups.gid, groups.grpname
FROM users u, groups g, grouplink gl
WHERE g.id = gl.gid
AND gl.uid = u.uid
When the user-id is in the variable $iUserId you could query following sql string:
$sSql = "SELECT groups.`grpname` FROM groups
INNER JOIN grouplink ON groups.`gid` = grouplink.`gid`
WHERE grouplink.`uid` = '" . intval($iUserId) . "'";
$rRes = mysql_query($sSql);
$aGroups = array();
while (($aRow = mysql_fetch_array($rRes)) !== false) {
$aGroups[] = $aRow['grpname'];
}
Now all groups associated with the user are in the array $aGroups.

Categories