一切正常并与数据库通信,但无论有多少用户在线,它都会保持1
我有为num rows和query
创建的辅助函数在线用户
function users_online(){
$session = session_id();
$time = time();
$time_out_in_seconds = 60;
$time_out = $time = $time_out_in_seconds;
$sql = "SELECT * FROM users_online WHERE session = '$session'";
$result = query($sql);
$count = row_count($result);
if ($count == NULL) {
$sql= "INSERT INTO users_online(session, time) VALUES ('$session','$time')";
query($sql);
} else {
$sql= "UPDATE users_online SET time = '$time' WHERE session = '$session'";
query($sql);
}
$sql = "SELECT * FROM users_online WHERE time > '$time_out'";
return $count_user = row_count($result);
}
DB Config Helper功能
$connection = mysqli_connect('localhost', 'root', '', 'danger_db');
function row_count($result)
{
return mysqli_num_rows($result);
}
function escape($string)
{
global $connection;
return mysqli_real_escape_string($connection, $string);
}
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
function confim($result)
{
global $connection;
if (! $result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
function fetch_array($result)
{
global $connection;
return mysqli_fetch_array($result);
}
数据库表
CREATE TABLE IF NOT EXISTS `users_online` (
`id` int(11) NOT NULL,
`session` varchar(255) NOT NULL,
`time` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=31 ;
--
-- Dumping data for table `users_online`
--
INSERT INTO `users_online` (`id`, `session`, `time`) VALUES
(30, 'n3kppn4lp0n9h4gdm7a6rh84b2', 1452969896),
(29, 'mqhrkr2b3f2rga1vhqh4t6pe23', 1452969689),
(28, 'dpg2nmsrvsvottj9k7ot1gvcm6', 1452969893);
答案 0 :(得分:1)
$time = time();
$time_out_in_seconds = 60;
$time_out = $time = $time_out_in_seconds;
你想在这做什么?您将time_out
和 $time
设置为等于$time_out_in_seconds
。因此,您要将所有三个值都设置为60
静态值。
然后在代码中稍后将值60
保存到数据库中,然后调用time > '$time_out'
SQL,这样您就可以将用户设置为在线,始终为60,然后始终询问数据库,用于返回大于 60的行。
将上述代码替换为:
$time = time();
$time_out_in_seconds = 60;
$time_out = $time - $time_out_in_seconds;
//edit this will further down the page show all users who
//updated within the last 60 seconds.
现在这意味着您的SQL查询将检查会话与当前时间的时间,以及使用当前时间更新会话。这应该会给你更好的结果。
您的代码末尾的编码也很差:
$sql = "SELECT * FROM users_online WHERE time > '$time_out'";
return $count_user = row_count($result);
返回获取值并将其传递回调用脚本,此值是您希望在线提供用户数的值,但返回值是多少?它由row_count($result)
组成。什么是$result
?最后一行$sql
是获取结果所需的行,但此行与结果变量无关。
您错过了一行,因此您需要重新插入第$result = query($sql);
行:
$sql = "SELECT * FROM users_online WHERE time > '$time_out'";
$result = query($sql);
return row_count($result);
}
现在,这将为您提供当前在线用户返回的行数的数值,作为函数users_online();
的结果