如何首先从不同的SQL表(PHP)获取不同的相关值

时间:2010-03-15 23:44:36

标签: php mysql html forms request

我很想填写选项列表。我有2个表USERS和STREAMS我想要获取所有流并获得分配给该流的用户名。

用户包含用户名和ID

Streams由id,userID,streamID

组成

我尝试这样的代码:

<?php           
        global $connection;
        $query = "SELECT * 
        FROM streams ";
        $streams_set = mysql_query($query, $connection);
        confirm_query($streams_set);    
    $streams_count = mysql_num_rows($streams_set);
    while ($row = mysql_fetch_array($streams_set)){
            $userid = $row['userID'];
                global $connection;
        $query2 = "SELECT email, username ";
        $query2 .= "FROM users ";
        $query2 .= "WHERE id = '{$userid}' ";

        $qs = mysql_query($query2, $connection);
        confirm_query($qs); 
        $found_user = mysql_fetch_array($qs);


 echo ' <option value="'.$row['streamID'].'">'.$row['userID'].$found_user.'</option> ';
}
    ?>

但它不会从DB =返回USER名称(那么我该怎么做才能将用户名视为“选项”文本?

1 个答案:

答案 0 :(得分:2)

您可以在流上包含JOIN的一个查询执行此操作.userID = users.id

$query = "
  SELECT
    s.streamId,
    s.userId,
    u.username
  FROM
    streams as s
  JOIN
    users as u
  ON
    s.userId=u.id
  ";
$result = mysql_query($query, $connection);
confirm_query($result);
echo '<option value="">Debug: #rows=', mysql_num_rows($row), '"</option>';

while ( false!==($row=mysql_fetch_array($result)) ) {
  sprintf('<option value="%s">id:%s name:%s</option>',
    $row['streamID'], // you probably should apply htmlspecialchars()
    $row['userID'], // on these two, too.
    htmlspecialchars($row['username'])
  );
}