开发者

How to first get different related values from different SQL tables (PHP)

开发者 https://www.devze.com 2022-12-22 20:41 出处:网络
I am triig to fill options list. I have 2 tables USERS and STREAMS I vant to get all streams and get names of users assigned to that streams.

I am triig to fill options list. I have 2 tables USERS and STREAMS I vant to get all streams and get names of users assigned to that streams.

Users consists of username and id

Streams consists of id, userID, streamID

I try such code:

<?php           
        global $connection;
        $query = "SELECT * 
        FROM streams ";
        $streams_set = mysql_query($query, $connection);
        confir开发者_运维问答m_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> ';
}
    ?>

But it does not return USER names from DB=( So what shall I do to this code to see usernames as "options" text?


You can do this with one query containing a JOIN on 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

精彩评论

暂无评论...
验证码 换一张
取 消