我正在为我的小管理面板编写代码,由于我不是那么高级的编码员,我在使用两个不同的表获取名称时遇到了一些麻烦。
到目前为止,这是我的代码:
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
include 'db_connect.php';
$sql = "SELECT * FROM $tbl_name WHERE is_dead='0'";
$result=mysql_query($sql);
?>
<title>Title</title>
<center><img src="header.png"></center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<? include 'menu.php';?>
</tr>
<tr>
<td align="center"><strong>ID</strong></td>
<td align="center"><strong>Unique ID</strong></td>
<td align="center"><strong>Model</strong></td>
<td align="center"><strong>Last Online</strong></td>
<td align="center"><strong>Options</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['id']; ?></td>
<td><? if ($rows['unique_id'] == 7815684) { echo '<font color="blue"><b><u>7815684</u></b></font>'; }
elseif ($rows['unique_id'] == 2312964) { echo '<font color="blue"><b><u>2312964</u></b></font>'; }
else { echo $rows['unique_id']; } ?></td>
<td><? echo $rows['model']; ?></td>
<td align='center'><font color="green"><b><? echo $rows['last_updated']; ?></b></font></td>
<td align="center"><a href="update.php?id=<? echo $rows['id']; ?>">update</a>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
所以我要做的是获取用户名,使用两个表 $tbl_name
和 $prtalbe
使用它们的 unique_id。因此,如果来自 $tbl_name
的 unique_id 等于来自 $prtable
的 unique_id,我想显示来自 $prtalbe
的用户名。
我一直在尝试另一个 sql 查询:
$sql = "SELECT * FROM $tbl_name, $prtable WHERE $tbl_name.unique_id = $prtable.unique_id;
$result=mysql_query($sql);
然后执行 while 循环使其工作
while($rows=mysql_fetch_array($result)){
$rows['name'];
}
它确实有效,但它不想将它直接放入我的代码中,因为 ID
来自 $prtable
和 $tbl_name
是不同的。
最佳答案
试试这个:
$sql = "SELECT $prtable.username FROM $tbl_name INNER JOIN $prtable ON ($tbl_name.unique_id = $prtable.unique_id)";
当您调用 INNER JOIN
时,您将从每个表中获取所有行,并在给定 ON
条件的情况下组合它们。有关详细信息,请参阅:http://www.w3schools.com/sql/sql_join_inner.asp
关于php - 如果来自两个不同表的 ID 相等,则显示来自另一个表的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18109211/