Getting rows from multiple table - PHP and loop - php

I'm trying to search for all the parent category of child category from 2 tables
Sample database
table1 table2
+------------+-------------+ +------------+-------------+
|Categ_name |Categ_parent | |Temp_name |Temp_parent |
+------------+-------------+ +------------+-------------+
|Items |0 | |Cookware |Kitchen |
|House |Item | |Utensils |Cookware |
|Car |Item | +------------+-------------+
|Kitchen |House |
|Living Room |House |
|Appliance |Living Room |
+------------+-------------+
if I search for 'Utensils', hoping to get
Categories :
Cookware
Kitchen
House
Items
as a result but I'm a little confused with SQL.
$i='Utensils';
while($i!='0'){
$sql="SELECT m.Categ_parent AS parent,t.Temp_parent AS parent, FROM table1 AS m,table2 AS t WHERE m.Categ_name='".$i."' OR t.Temp_name='".$i."' LIMIT 1";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_array($result);
$i=$row['parent'];
echo $i;
}
I'm not getting any result or error from this code

For repeatedly accessing the same table, you might be better off using a stored procedure.
## Create a view so that we can work more easily with the tables
create view items as select Categ_name as name, Categ_parent as parent from table1
union (select Temp_name as name, Temp_parent as parent from table2);
name parent
-------------------------
Item 0
House Item
Car Item
Kitchen House
Living Room House
Appliance Living Room
Cookware Kitchen
Utensils Cookware
DROP PROCEDURE IF EXISTS selectName;
CREATE PROCEDURE selectName(IN currentName VARCHAR(100))
BEGIN
drop temporary table if exists tmp_results;
create temporary table tmp_results (
name varchar(100)
);
while (exists(select parent from items where name = currentName)) DO
select parent into currentName from items where name = currentName;
insert into tmp_results select currentName;
END WHILE;
select * from tmp_results;
END;
To use this procedure:
call selectName('Utensils');
Cookware
Kitchen
House
Item
0
PHP code to initialize database (run the statements only ONCE to create the view and stored procedure):
// create view
$mysqli->query("
drop view if exists viewItems;
create view viewItems as select Categ_name as name, Categ_parent as parent from table1
union (select Temp_name as name, Temp_parent as parent from table2)";
");
// create stored procedure
$mysqli->query("
DROP PROCEDURE IF EXISTS selectParents;
CREATE PROCEDURE selectParents(IN currentName VARCHAR(100))
BEGIN
drop temporary table if exists tmp_results;
create temporary table tmp_results (
name varchar(100)
);
while (exists(select parent from viewItems where name = currentName)) DO
select parent into currentName from viewItems where name = currentName;
insert into tmp_results select currentName;
END WHILE;
select * from tmp_results;
END"
);
PHP code to query
$name = mysqli_real_escape_string($name);
$results = $mysqli->query("CALL selectParents($name)");

at first the SQL you wrote has an error which is the "," before "from ...".
I suggest using UNION instead of the current SQL command. The current command will mix two parent values and one of which may not be right.
Try the following solution, which works good on my computer:
$i='Utensils';
while($i!='0'){
$sql="(SELECT Categ_parent as parent from table1 WHERE Categ_name='".$i."')
UNION
(SELECT Temp_parent as parent from table2 where Temp_name='".$i."')";
$result = mysqli_query($con,$sql);
if($result && mysqli_num_rows($result)){
$row = mysqli_fetch_array($result);
$i = $row["parent"];
}
else{
$i = '0';
}
echo $i."<br>";
}

Related

Need help in joining two tables from mysql database for a photography project

I am working on a photography project and I am facing a bit issue with joining tables and retrieving data from mysql database.
I have created two tables for this project. One table named cm_team is for team members and another table named cm_events for photography events..Assume to shoot a event, we require 6 persons and the id of the person is stored in cm_events table.
As you can see from the above images.. I am storing the id's of members of cm_team in cm_events table.. I wish to obtain the name of the team member in the respective highlighted fields in the cm_events table..Any help is highly appreciated.
for example my desired output should be: instead of 5 under team_lead heading, I should get the name corresponding to 5 i.e Arjun
Something like this? (cleaner and faster than subqueries)
SELECT
`event`.client_name,
`event`.client_number,
# some more event cols ..
`team_lead`.`cm_name` AS `team_lead`,
`candid_photo`.`cm_name` AS `candid_photo`,
`candid_video`.`cm_name` AS `candid_video`,
`traditional_photo`.`cm_name` AS `traditional_photo`,
`traditional_video`.`cm_name` AS `traditional_video`,
`helper`.`cm_name` AS `helper`
FROM cm_events `event`
JOIN cm_team `team_lead` ON `team_lead`.`cm_code` = `event`.`team_lead`
JOIN cm_team `candid_photo` ON `candid_photo`.`cm_code` = `event`.`candid_photo`
JOIN cm_team `candid_video` ON `candid_video`.`cm_code` = `event`.`candid_video`
JOIN cm_team `traditional_photo` ON `traditional_photo`.`cm_code` = `event`.`traditional_photo`
JOIN cm_team `traditional_video` ON `traditional_video`.`cm_code` = `event`.`traditional_video`
JOIN cm_team `helper` ON `helper`.`cm_code` = `event`.`helper`
With Sub queries
DROP TABLE IF EXISTS T,t1;
CREATE TABLE T (
id int, name varchar(10));
insert into t values
(1 , 'aaa'),
(2 , 'bbb');
create table t1 (
id int, team_lead int,team_a int);
insert into t1 values
(1,1,2),
(2,2,2);
select t1.id, (select t.name from t where t.id = t1.team_lead) team_lead,
(select t.name from t where t.id = t1.team_a) team_a
from t1;
+------+-----------+--------+
| id | team_lead | team_a |
+------+-----------+--------+
| 1 | aaa | bbb |
| 2 | bbb | bbb |
+------+-----------+--------+
2 rows in set (0.001 sec)

Find Staff in Child Departments - PHP

I am building a project with an organization chart using Codeigniter + MySQL + Active Record.
There are departments listed as organization tree, Staff for information of the persons, Staff Roles and Staff_Departments where i store the matching:
Department - Staff - Role
You can see the structure below:
Departments (parent_id is used to build the tree)
Staff (raw Staff information)
Staff Roles (the lowest the weight, the highest in hierarchy)
Staff Departments (In which department - Who - What Role)
In a later phase, a Staff will probably belong in 2 or more departments with different roles. That's why i used a separate table Staff_departments for many-to-many. In this case, let's keep it simple and assume that 1 Staff belongs to 1 Department.
What i am trying to do:
A Manager(role weight=0 || role_id=1) in a Department, can view the Staff(Employees AND Supervisors) who work in his Department AND all the Staff(Employees AND Supervisors) from the Departments that are Children of his Department. The depth of the tree is unknown.
A Supervisor can view the Staff(only Employees) who work only in his Department.
An Employee can only view himself.
For Supervisors and Employees, the process is simple, so i think i am ok with that. For Managers probably i have to do something recursive, but i'm struggling every time i'm starting writing some lines of code.
My idea is to have a function find_related_staff($staff_id) {} in my controller, which i will pass the ID of the Staff who is logged in and it will return an array with the IDs of his related Staff. The only thing i got, is the ID of the Staff who is logged in.
If Manager return IDs of Managers,Supervisors and Employees related in his Department AND Managers,Supervisors and Employees from
Child Departments of his Department.
If Supervisor return IDs of Supervisors and Employees related in his Department only.
If Employee return his ID
Any idea on how to achieve that?
Ok, I think that, in order to make things easier to understand, we need to break your problem into small pieces (and I'm only focus on the section that you say you really need help: the managers' recursion).
First, we get the current department associated with the user authenticated. As you've said, you only have the ID of the staff currently sign so we'll start with that. Let's say the user id is assigned to variable $user_id.
$user_department = $this->db->get_where('staff_departments', ['staff_id' => $user_id])->row();
Now that we have the department, we check to see what's the role of the user in that department. We'll add that info to the $user_department object:
$user_department->role = $this->db->get_where('staff_roles', ['role_id' => $user_department->role_id])->row();
Let's check the weight of the user's role, shall we? If it's 0, we know it's a manager on that department so we'll recursively find the nested departments and their staff information. As per your logic dictates, we can check, here, if the user is a supervisor, also, and escalate if necessary. Like this:
if ($user_department->role->role_weight <= 1) {
// the user is a supervisor OR a manager, but both those can see, at least, the current department's staff information
$user_department->staff = $this->db->get_where('staff_departments', ['department_id' => $user_department->department_id]);
// now is the user a manager? If so, let's find nested departments
if ($user_department->role->role_weight === 0) {
$user_department->childs = $this->getChildDepartmentsAndStaffOf($user_department->department_id);
}
}
As you may note, there's a function that'll be called recursively. It must be something along this lines:
public function getChildDepartmentsAndStaffOf($department_id)
{
$child_departments = $this->db->get_where('departments', ['parent_id' => $department_id]);
if (! $child_departments) {
return null;
}
foreach ($child_departments as &$department) {
$department->staff = $this->db->get_where('staff_departments', ['department_id' => $department->department_id]);
$department->childs = $this->getChildDepartmentsAndStaffOf($department->department_id);
}
return $child_departments;
}
Now, you have the structure you want. I know this might be refactored, but I think that is enough to get your answer and point you to the right path.
Hope I've helped a little.
Yes, to get it done you must use recursive procedures. (I'm using MySQL 5.6.19)
I have created some test data before the stored procedures:
Sample data based on your question requirements:
create table departments
(
id int not null primary key auto_increment,
parent_id int,
department_name varchar(100)
);
insert into departments (id,parent_id,department_name)
values
(1,0,'Test A'),
(2,1,'Test B'),
(3,2,'Test C');
create table staff
(
id int not null primary key auto_increment,
ip_address varchar(100),
username varchar(100)
);
insert into staff values
(1,'127.0.0.1','ats'),
(2,'127.0.0.1','admin'),
(3,'127.0.0.1','george'),
(4,'127.0.0.1','jhon')
;
create table staff_roles
(
role_id int not null primary key auto_increment,
role_name varchar(100),
role_height int
);
insert into staff_roles values
(1,'Manager',0),
(2,'Supervisor',1),
(3,'Employee',2)
;
create table staff_departments
(
staff_department_id int not null primary key auto_increment,
department_id int,
staff_id int,
role_id int
);
insert into staff_departments values
(1,1,2,1),
(2,2,1,2),
(3,3,3,3),
(4,3,4,3);
It's time to create the stored procedures:
find_related_staff is the procedure that receives the staff_id parameter, according to that value will find the role_id in staff_departments table.
The variable #result will accumulate the final result as comma separated values.
find_recursive is the procedure that search in child departments and get the staff_id into #result variable;
The procedure code:
delimiter $$
drop procedure if exists find_related_staff$$
create procedure find_related_staff(p_id int)
begin
declare p_role_id int;
declare p_department_id int;
declare p_return varchar(255) default '';
declare p_role varchar(100);
select d.role_id, d.department_id, r.role_name
into p_role_id,p_department_id, p_role
from staff_departments d
inner join staff_roles r on d.role_id = r.role_id
where d.staff_id = p_id
limit 1;
case p_role_id
when 3 then -- employee (return the same id)
set #result = p_id;
when 2 then -- supervisor
select group_concat(s.staff_id)
into #result
from staff_departments s
where
s.role_id = 3
and s.department_id in
( select d.id
from departments d
where d.parent_id = p_department_id )
and s.role_id <> p_id;
when 1 then -- manager (complex recursive query)
select coalesce(group_concat(s.staff_id),'')
into #result
from staff_departments s
where
s.department_id = p_department_id
and s.staff_id <> p_id;
-- here we go!
call find_recursive(p_department_id);
end case;
select #result as result, p_role as role;
end $$
delimiter ;
delimiter $$
drop procedure if exists find_recursive$$
create procedure find_recursive(p_dept_id int)
begin
declare done int default false;
declare p_department int default false;
declare tmp_result varchar(255) default '';
-- cursor for all depend departments
declare c_departments cursor for
select s.department_id
from staff_departments s
where
s.department_id in
( select d.id
from departments d
where d.parent_id = p_dept_id );
declare continue handler for not found set done = true;
-- getting current departmens
set tmp_result =
(select coalesce(group_concat(s.staff_id),'')
from staff_departments s
where
s.department_id in
( select d.id
from departments d
where d.parent_id = p_dept_id ));
if length(tmp_result) > 0 then
if length(#result) > 0 then
set #result = concat(#result,',',tmp_result);
else
set #result = tmp_result;
end if;
open c_departments;
read_loop: loop
fetch c_departments into p_department;
if done then
leave read_loop;
end if;
call find_recursive(p_department);
end loop;
close c_departments;
end if;
end $$
delimiter ;
Testing:
Important: The max deep in recursion is 0 as default, we must change that value:
SET max_sp_recursion_depth=255;
Now we have the bellow configuration on your staff_departments table:
+---------------------+---------------+----------+---------+
| staff_department_id | department_id | staff_id | role_id |
+---------------------+---------------+----------+---------+
| 1 | 1 | 2 | 1 |
| 2 | 2 | 1 | 2 |
| 3 | 3 | 3 | 3 |
| 4 | 3 | 4 | 3 |
+---------------------+---------------+----------+---------+
Running each case:
call find_related_staff(2);
+--------+---------+
| result | role |
+--------+---------+
| 1,3,4 | Manager |
+--------+---------+
call find_related_staff(1);
+--------+------------+
| result | role |
+--------+------------+
| 3,4 | Supervisor |
+--------+------------+
call find_related_staff(3);
+--------+----------+
| result | role |
+--------+----------+
| 3 | Employee |
+--------+----------+
call find_related_staff(4);
+--------+----------+
| result | role |
+--------+----------+
| 4 | Employee |
+--------+----------+
Enjoy!
I think the most powerfull schema for hierarchical data in a relational database is the transitive-closure-table.
Given your sample data for the departments table:
department_id | parent_id | department_name
--------------|-----------|----------------
1 | 0 | TEST A
2 | 1 | TEST B
3 | 2 | TEST C
Your closure table (let's just call it departments_tree) would be like:
super_id | sub_id
---------|-------
1 | 1
1 | 2
1 | 3
2 | 2
2 | 3
3 | 3
Read it as: super_id = superordinate department_id; sub_id = subordinate department_id.
Assuming the logged-in user is manager of department with department_id = 2, the query to get all "supervised" employees is:
SELECT DISTINCT s.*
FROM departments_tree t
JOIN stuff_departments sd ON sd.department_id = t.sub_id
JOIN staff s ON s.id = sd.staff_id
WHERE t.super_id = 2
You can use triggers to populate and update the closure table.
Insert trigger:
DELIMITER //
CREATE TRIGGER `departments_after_insert` AFTER INSERT ON `departments` FOR EACH ROW BEGIN
INSERT INTO departments_tree (super_id, sub_id)
SELECT new.department_id, new.department_id
UNION ALL
SELECT super_id, new.department_id
FROM departments_tree
WHERE sub_id = new.parent_id;
END//
DELIMITER ;
Delete trigger:
DELIMITER //
CREATE TRIGGER `departments_before_delete` BEFORE DELETE ON `departments` FOR EACH ROW BEGIN
DELETE FROM departments_tree
WHERE sub_id = old.department_id;
END//
DELIMITER ;
Update trigger:
DELIMITER //
CREATE TRIGGER `departments_before_update` BEFORE UPDATE ON `departments` FOR EACH ROW BEGIN
DELETE t
FROM departments_tree p
CROSS JOIN departments_tree c
INNER JOIN departments_tree t
ON t.super_id = p.super_id
AND t.sub_id = c.sub_id
WHERE p.sub_id = old.parent_id
AND c.super_id = new.department_id;
INSERT INTO departments_tree (super_id, sub_id)
SELECT p.super_id, c.sub_id
FROM departments_tree p
CROSS JOIN departments_tree c
WHERE p.sub_id = new.parent_id
AND c.super_id = new.department_id;
END//
Note
You will not need a delete trigger, if you use foreighn keys with ON DELETE CASCADE:
CREATE TABLE `departments_tree` (
`super_id` INT(10) UNSIGNED NOT NULL,
`sub_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`super_id`, `sub_id`),
INDEX `sub_id_super_id` (`sub_id`, `super_id`),
FOREIGN KEY (`super_id`) REFERENCES `departments` (`department_id`) ON DELETE CASCADE,
FOREIGN KEY (`sub_id`) REFERENCES `departments` (`department_id`) ON DELETE CASCADE
);
Note 2
In many implementations of a transitive closure table, you will find a depth or level column.
But you don't need it for the given requirements. And I believe you will never really need it,
as long as you don't try to format tree output in SQL.
I think your main problem is how to traverse down so that will be solved by getRecursiveDepts(). I have not completed the code but you can try something like this
file db.php
class DB {
private $servername = "127.0.0.1";
private $username = "root";
private $password = "root";
private $dbname = "test";
private $port = '3306';
public function getRecursiveDepts($deptIds) {
if (!is_array($deptIds)) {
$deptIds = array($deptIds);
}
$sql = "SELECT id FROM Departments WHERE parentId IN (";
$sql .= implode(', ', $deptIds);
$sql .= ")";
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname, $this->port);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$newDept = array();
while($row = $result->fetch_assoc()) {
array_push($newDept, $row['id']);
}
$conn->close();
$moreDepts = $this->getRecursiveDepts($newDept);
if (is_null($moreDepts)) {
$finalIds = array_unique(array_merge($deptIds, $newDept));
} else {
$finalIds = array_unique(array_merge($deptIds, $newDept, $moreDepts));
}
return $finalIds;
} else {
$conn->close();
return null;
}
}
public function getRoles($empId) {
$sql = "SELECT role_id, department_id FROM staff_departmen_role WHERE staff_id = '$empId' GROUP BY role_id, department_id";
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname, $this->port);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$emp = array();
while($row = $result->fetch_assoc()) {
if (!array_key_exists($row['role_id'], $emp)) {
$emp[$row['role_id']] = array();
}
array_push($emp[$row['role_id']], $row['department_id']);
}
}
$conn->close();
return $emp;
}
public function getEmpDetails($empId) {
$sql = "SELECT role_id, department_id FROM staff_departmen_role WHERE staff_id = '$empId' GROUP BY role_id, department_id";
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname, $this->port);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$emp = array();
while($row = $result->fetch_assoc()) {
if (!array_key_exists($row['role_id'], $emp)) {
$emp[$row['role_id']] = array();
}
array_push($emp[$row['role_id']], $row['department_id']);
}
}
$conn->close();
return $emp;
}
}
file index.php
<?php
include_once 'db.php';
$objDB = new DB();
$empId = 2;
$emps = $objDB->getRoles($empId);
foreach ($emps as $roleId => $deptIds) {
switch ($roleId) {
case 1:
$allDeptIds = $objDB->getRecursiveDepts($deptIds);
break;
case 2://Supervisor GetEmpIds of current dept role >= 2
break;
case 3://Employee GetEmpIds of current dept role >= 2
$emp = $objDB->getEmpDetails($empId);
break;
default:
# code...
break;
}
}
$data = $objDB->getRecursiveDepts($empId);
print_r($data);
?>

PHP MySQL Group BY Having issue

Suppose I have a table like:
ID|Word |Reference
1 |Dog |1
1 |Fish |2
1 |Sheep|3
2 |Dog |4
2 |Fish |5
3 |Sheep|6
4 |Dog |7
I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:
SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'
However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)
Basically the problem is the AND statement over multiple rows with the same ID.
UPDATE:
I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:
SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING count(DISTINCT Word) = 2;
Thanks
Here are two solutions that return the correct records, the first as individual records by ID and Reference, and the second with one record per ID and the Words and References as comma separated in columns.
Setup table and populate rows:
DROP TABLE IF EXISTS `list1`;
CREATE table `list1` (
id int(10),
Word varchar(10),
Reference int(10)
);
INSERT INTO `list1` (`ID`, `Word`, `Reference`)
VALUES
(1, 'Dog',1),
(1 ,'Fish',2),
(1 ,'Sheep',3),
(2 ,'Dog',4),
(2 ,'Sheep',5),
(3 ,'Sheep',6),
(4 ,'Dog',7);
Returns one row for each combination of ID and Word
SELECT
t.`ID`,
t.`Word`,
t.`Reference`
FROM `list1` as t
JOIN (
SELECT
t1.`ID` as `ref_id`
FROM `list1` AS t1
WHERE `Word` in ('Sheep','Dog')
GROUP BY t1.`ID`
HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
ORDER BY t.`ID`,t.`Word`;
Results
ID | Word | Reference
1 | Dog | 1
1 | Sheep | 3
2 | Dog | 4
2 | Sheep | 5
Returns one row per ID, with a comma separated list of Words in one column, and a comma separated list of Reference in another.
SELECT
t.`ID`,
GROUP_CONCAT(t.`Word`) AS `Words`,
GROUP_CONCAT(t.`Reference`) AS `References`
FROM `list1` as t
JOIN (
SELECT
t1.`ID` as `ref_id`
FROM `list1` AS t1
WHERE `Word` in ('Sheep','Dog')
GROUP BY t1.`ID`
HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
GROUP BY t.`ID`
ORDER BY t.`ID`,t.`Word`;
Results:
ID | Words | References
1 | Dog,Sheep | 1,3
2 | Dog,Sheep | 4,5
You need to join the table on itself. This way you can pick up where the id's are the same for instances where dog and sheep overlap.
Try this:
declare #t table (id int , Word varchar(10) )
insert into #t (ID, Word) values (1, 'Dog'),
(1 ,'Fish'),
(1 ,'Sheep'),
(2 ,'Dog'),
(2 ,'Sheep'),
(3 ,'Sheep'),
(4 ,'Dog')
select t.ID
from #t as t
join #t as t1 on t1.id = t.id
where t.word = 'Dog' and t1.word = 'Sheep'
Here's one way to do it by joining your table to itself.
SELECT t1.id FROM `Table` t1
INNER JOIN `Table` t2 ON t1.id = t2.id
WHERE t1.word='Dog' AND t2.word='Sheep';
The answer for my problem is solved using underneath query:
SELECT ID, GROUP_CONCAT(Reference) as ReferencesGrouped FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING count(DISTINCT Word) = 2;
This will return me:
ID|ReferencesGrouped
1 |1,4
2 |4,5

SELECT data from two tables with same name

I've tried to find a way to select data from two tables within the same query as follows:
Suppose I have this as table1
id | item | qty
1 | 1bb1 | 12
2 | 1cc1 | 10
and as table2
id | item | qty
6 | 1bb1 | 12
7 | 1vv1 | 4
And I have an imported file which contains data item as $sheetData[$i]['A'] from an excel sheet that I need to use it to find out if BOTH tables have this item or not.
My code as follows :
$query1="SELECT * FROM table1.item,table2.item WHERE item ='".$sheetData[$i]['A']."'";
$result1= mysql_query($query1);
if(mysql_num_rows($result1)>0){
echo "This Item Found in Both Tables";
echo $sheetData[$i]['A'];
echo "<br />";
}
else{
echo "Item Could Not Be Found in both tables";
echo $sheetData[$i]['A'];
}
Its basically I want to find out if the imported item found in both tables or not. I hope this makes sense for you!
Any help would be really appreciated
Compiler can't decide which item needs to compare. item from table1 or item from table2
So write query as:
SELECT A.* , B.*
FROM table1 A, table2 B
WHERE A.item = B.item AND
A.item = '".$sheetData[$i]['A']."'
Try with -
"SELECT t1.id, t1.item, t1.qty, t2.id id_2, t2.qty qty_2 FROM table1 t1
INNER JOIN table2 t2 ON t2.item = t1.item
WHERE table1.item ='".$sheetData[$i]['A']."'"
Try to avoid using mysql, it is deprecated now. mysqli/PDO instead.
Try something like this:
SELECT COUNT(*)
FROM (
SELECT DISTINCT 1
FROM table1
WHERE item = ?
UNION ALL
SELECT DISTINCT 1
FROM table2
WHERE item = ?) AS t
This will return 2 if the item exists in both tables, 1 if it exists in only 1 table and 0 if the item doesn't exists in any of the two tables.

PHP/MySQL - Trouble when trying to select two columns where id from table1 is equal to id from table2

Here is my query:
$query = 'SELECT * extensa_econt_city as econt_city, extensa_econt_office as econt_office WHERE econt_city.city_id = econt_office.city_id';
I am trying to select all the rows from table extensa_econt_city and extensa_econt_office where city_id from extensa_econt_city is equal to city_id from extensa_econt_office.
Then when i get this information i have to create FORECH loop. It is important to be FORECH not while loop.
Here is my sample code:
<?PHP
foreach($results as $row){
echo $row['econt_city.name'];
echo $row['econt_office.name'];
}
?>
In this foreach loop i have to select row name from extensa_econt_office and extensa_econt_city.
Structure:
I hope you understand what i am asking.
Can you help me out resolve this problem.
Thanks in advance!
I think this might do what you mean.
select
c.`city_id`,
c.`post_code`,
c.`type`,
c.`name`,
c.`name_en`,
c.`zone_id`,
c.`country_id`,
c.`office_id`
o.`FIELD_NAME` as 'ALIAS',
o.`NEW_FIELD_NAME` as 'OTHER ALIAS'
from `extensa_econt_city` c
left outer join `extensa_econt_office` o on o.`city_id`=c.`city_id`
Once the tables are aliased ( in this case the aliases are c & o ) you can select either all records using * ( unless there are duplicated names in which case you would get an error ) or, as above, select the desired fields directly in the query.
Once the query is set the FOREACH loop can select he record by the name / alias defined in the sql
All you are looking for is the name column, not all columns (select *) from what you have shown. Don't drag down your system with wildcards as such (with select *). Also do an explicit join.
Here is a visual of my pretend schema, as I am not suggesting it is yours.
Do an explicit join, unlike your join in a where clause (that style is circa 1995)
Schema
create table extensa_econt_city
( id int auto_increment primary key,
city_id int not null,
name varchar(100) not null
);
create table extensa_econt_office
( id int auto_increment primary key,
city_id int not null,
name varchar(100) not null
);
insert extensa_econt_city(city_id,name) values (1,'eec name1'),(2,'eec name2'),(3,'eec name3');
insert extensa_econt_office(city_id,name) values (1,'EEO name1'),(2,'EEO name2'),(3,'EEO name3');
The Query
select eec.name as eec_name,eeo.name as eeo_name
from extensa_econt_city eec
join extensa_econt_office eeo
on eeo.city_id=eec.city_id;
Results
+-----------+-----------+
| eec_name | eeo_name |
+-----------+-----------+
| eec name1 | EEO name1 |
| eec name2 | EEO name2 |
| eec name3 | EEO name3 |
+-----------+-----------+
I am trying to select all the rows from table extensa_econt_city and
extensa_econt_office where city_id from extensa_econt_city is equal to
city_id from extensa_econt_office...
In this foreach loop I have to select row name from extensa_econt_office and extensa_econt_city.
SELECT eec.name AS ee_city_name,
eeo.name AS ee_office_name,
FROM extensa_econt_city eec
LEFT JOIN extensa_econt_office eeo ON eec.city_id = eeo.city_id
And in the PHP foreach loop, you can access the data like this:
<?php
foreach($results as $row){
echo $row['ee_city_name'];
echo $row['ee_office_name'];
}

Categories