我有一个查询,它将显示与其他表相关的表的字段/值。使用 foreach 循环,我可以在 html 中显示这些字段/值。但我想显示"foreign_name"而不是"foreign_id"。
<?php foreach ($table_related as $table): ?>
<?php echo $table['id']; ?>
<?php echo $table['foreign_id']; ?>//the foreign key, it should be foreign_name
<?php echo $table['name'];?>
<?php endforeach; ?>
classeManageService.php
function showAllServices()
{
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
$rowcount = $query->rowCount();
if($rowcount > 0)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowcount;
}
return $result;
}
//show_all.php
<?php
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$show_all_services = $init->showAllServices();
?>
"my_table"有列 ID,my_name,foreign_id,other_table"有列 foreign_id,foreign_name,foreign_desc
我可以在 html 中显示所有这些值。但是,如何显示其他字段而不是其他表中的 id?我必须更改我的查询吗?有什么想法吗?
你必须用一个JOIN
做一个查询:
由于您没有提供其他表名,因此请考虑otherTable
,service_id
为外键。
查询示例:
$query = $this->link->query("SELECT * FROM services s, otherTable o WHERE s.id = o.service_id ORDER BY s.id DESC");
现在,在结果集中,您还将拥有所有otherTable
字段,您可以从中获取所需的名称。
好的,我明白了,我更改了查询从
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
到
$query = $this->link->query("SELECT services.*, services_type.name FROM services JOIN services_type USING(services_id)") ;
现在它正在工作,是的。