[英]How to retrieve data from a one to many sql relationship using PHP
I have two tables.我有两张桌子。 One is called "employee" and has a column named "role".
一个被称为“员工”,并有一个名为“角色”的列。 I have another table with the name "role" that has two columns in it "role_id" and "name".
我有另一个名为“role”的表,其中有两列“role_id”和“name”。
I have linked the two in MySQL with a foreign key (I think,).我已经用外键(我认为)将 MySQL 中的两者链接起来。 by going to relationship view through phpmyadmin and selecting the appropriate settings.
通过 phpmyadmin 进入关系视图并选择适当的设置。
Now in PHP I have the following code:现在在 PHP 我有以下代码:
$employees = "SELECT employee_id, first_name, last_name, role
FROM employee
WHERE status = 1";
$employee = mysqli_query($link, $employees);
foreach ($employee as $employeeInfo) {
<?php echo $employeeInfo['role'];?>
}
However, this returns the number I have assigned to the role in the employee's table.但是,这将返回我分配给员工表中角色的号码。 Not the name from the linked table.
不是链接表中的名称。
I think it has something to do with having to use the JOIN condition is the PHP code.我认为这与必须使用 JOIN 条件有关,即 PHP 代码。 However, doing some experimentation just gets me blank results.
然而,做一些实验只会让我得到空白的结果。
Do you have any tips for outputting the role name from the second table in this case?在这种情况下,您对从第二个表中输出角色名称有什么提示吗?
Thank you谢谢
Use join to get the name of the role.使用 join 获取角色的名称。
$employees = "SELECT a.employee_id, a.first_name, a.last_name, b.name as role
FROM employee a join role b on a.role = b.role_id
WHERE a.status = 1";
$employee = mysqli_query($link, $employees);
foreach ($employee as $employeeInfo) {
echo $employeeInfo['role'];
}
Inner Joins should really work...内连接应该真的有效......
SELECT employee_id, first_name, last_name, role.name as role
FROM employee
INNER JOIN role ON employee.role = role.role_id
WHERE status = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.