Get all id's from table MYSQL

时间:2015-10-30 22:55:56

标签: php mysql mysqli

I'd like to echo all ID's from the user table but I can't get it to work. I tried this below and searched some stacks but I can't find the right answer.

        $query = $db->query( "SELECT * FROM users" );
        $num   = $db->num( $query );
        while( $array = $db->assoc( $query ) ) {
            $active_ids = $array['id'];
        }

        $query = "SELECT u.username, u.habbo, count(*) AS n 
        FROM users u, timetable tt 
        WHERE u.id=tt.dj and u.id IN (".$active_ids.")
        GROUP BY tt.dj";

        $result = $mysqli->query($query);

        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()){
                echo "<tr id='uren-table-row'>";
                echo "<td width='60px'><div style='height:50px;padding-top:25px;overflow:hidden;float:left;margin-top:-25px;'><img style='margin-top:-28px;float:left;' src='http://habmoon.org/moonstream/dj?habbie={$row['habbo']}&amp;head_direction=3&amp;direction=2&amp;size=b&amp;hb=img&amp;gesture=sml'></div></td>";
                echo "<td width='200px' style='padding:0 15px;'>", $row['username'] ,"</td>";
                echo "<td style='padding:0 15px;'>Heeft <b>", $row['n'] ,"</b> Uur gedraait deze week</td>";
                echo "</tr>";
            }
        }

2 个答案:

答案 0 :(得分:3)

Remove count(*) AS n from your query. This will cause MySQL to return only 1 record.

You also have some errors in your first lines:

$active_ids = array();
while( $array = $db->assoc( $query ) ) {
    $active_ids[] = $array['id'];
}

You forgot to define $active_ids and add [].

答案 1 :(得分:2)

You need to make $active_ids a CSL. Currently you overwrite the id(s) on every iteration so you only getting the last one. You also need it separated by commas so use implode. Try:

while( $array = $db->assoc( $query ) ) {
            $active_ids[] = (int)$array['id'];
 }
 $active_ids = implode(',', $active_ids);