如果来自两个不同表的ID相等,则显示另一个表中的名称

时间:2013-08-07 16:51:19

标签: php mysql sql

我正在为我的小管理员面板编写代码,因为我不是那么高级的编码器,我在使用两个不同的表格获取名称时遇到了一些麻烦。

到目前为止,这是我的代码:

<?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的{​​{1}}不同。

1 个答案:

答案 0 :(得分:0)

试试这个:

$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