2010-03-15 52 views
0

我是triig来填充选项列表。我有2个表USERS和STREAMS我想要获取所有流并获取分配给这些流的用户名称。如何首先从不同的SQL表格获取不同的相关值(PHP)

用户包括用户名和ID

流由ID,用户ID的,流ID

我尝试这样的代码:

<?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 =(所以返回用户名我该怎么做这个代码来看用户名为“选项”文本?

+0

只要确定要做什么:每个用户只能在一个流上? – VolkerK 2010-03-15 23:49:23

+0

你的代码中有一个无限循环。如果你想让while语句成为你想要的循环,你应该把它写成@VolkerK。 – Young 2010-03-16 00:13:32

+0

@SpawnCxy:虽然我鼓励人们像我一样写循环条件,但它应该像Ole写的那样按预期工作。 – VolkerK 2010-03-16 08:32:04

回答

2

你可以做一个包含JOIN的查询在streams.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']) 
); 
} 
+0

顺便说一句,在你的代码中有一些关于beeg或small leters的错误(s.streamId - > $ row ['streamID']) – Rella 2010-03-17 01:31:24

+0

大多数时候我测试我发布的代码,有时候不会......在这种情况下;-)抱歉。 – VolkerK 2010-03-17 12:35:13

相关问题