简体   繁体   中英

PHP Query Doesn't Work

I have the following code, which should get some results from 2 tables, I'm currently trying to load their lastactive (time), user id, user avatar.

I'm using the following code to display this on a page:

<?php
            $t = 1800;
            $sql = 'SELECT mh_users.id, mh_users.lastactive, mh_users.avatar, mh_users.gang FROM `mh_users` ';
            $sql .= 'LEFT JOIN `mh_users_stats` ON mh_users.id = mh_users_stats.id WHERE mh_users.lastactive > `'.$t.'` ORDER BY `mh_users.lastactive` DESC';
            $res = $db->query($sql) or exit($db->error);
            while($row = $res->fetch_object()) {
                $online_user = new User($row->id);
                echo '<tr>'
                     . '<td><img src="'.$online_user->avatar.'" width="40" height="40" alt="[avatar]" /></td>'
                     . '<td>'.$online_user->formattedname.'</td>'
                     . '<td>'.$gang_name.'</td>'
                     . '</tr>'
                ;
            }
            ?>

It seems that with this query, the page is blank, $db->error doesn't return anything, the page is just white.

However, if I do it in this query:

$sql = 'SELECT mh_users.id, mh_users.lastactive, mh_users.avatar, mh_users.gang FROM `mh_users` ';
$sql .= 'LEFT JOIN `mh_users_stats` ON mh_users.id = mh_users_stats.id';

It does work, however, it doesn't ORDER at last active time, how can I make this query to list the results based on lastactive time (So the user that accessed a page the latest, will be shown at top)

Sorry for the noob question, but I can't get it fixed at the moment :(

Many thanks!

Instead of

ORDER BY `mh_users.lastactive`

you should have backtick alias and field name separately like this

ORDER BY `mh_users`.`lastactive`

or don't use backticks at all because you already don't use them everywhere in your query.

And as we find out in comments you forgot to add WHERE condition in your update statement. Something like this $sql = 'UPDATE mh_users SET lastactive = '.time().' WHERE id='.$_SESSION['uid']; $sql = 'UPDATE mh_users SET lastactive = '.time().' WHERE id='.$_SESSION['uid']; should work.

ORDER BY `mh_users`.`lastactive`

ORDER BY `mh_users.lastactive`

This should work for you (I just removed the back ticks around the variable):

$sql = 'SELECT mh_users.id, mh_users.lastactive, mh_users.avatar, mh_users.gang FROM `mh_users` ';
$sql .= 'LEFT JOIN `mh_users_stats` ON mh_users.id = mh_users_stats.id WHERE mh_users.lastactive > '.$t.' ORDER BY `mh_users.lastactive` DESC';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM