技术开发 频道

使用 PHP 在站点上构建类似 Twitter 的系统

  追随其他用户

  接下来可以将更多东西添加到 functions.php 文件中。这里需要一个 show_users() 函数,该函数可以返回系统中所有用户的一个列表。后面将使用这个函数填充一个用户列表。

  清单 10. show_users() 函数

function show_users(){
    $users
= array();
    $sql
= "select id, username from users where status='active' order by username";
    $result
= mysql_query($sql);

    
while ($data = mysql_fetch_object($result)){
        $users[$data
->id] = $data->username;
    }
    return $users;
}

  有了 show_users() 函数之后,接下来可以创建一个 users.php 文件,该文件将运行这个函数,并显示系统中所有用户的一个列表,对于每个用户,在用户名的旁边都有一个 follow 链接。

  清单 11. 运行 show_users() 函数的 users.php 文件

<?php
session_start();
include_once(
"header.php");
include_once(
"functions.php");

?
>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
    
<title>Microblogging Application - Users</title>
</head>
<body>

<h1>List of Users</h1>
<?php
$users
= show_users();

if (count($users)){
?
>
<table border='1' cellspacing='0' cellpadding='5' width='500'>
<?php
foreach ($users
as $key => $value){
    echo
"<tr valign='top'>\n";
    echo
"<td>".$key ."</td>\n";
    echo
"<td>".$value ." <small><a href='#'>follow</a></small></td>\n";
    echo
"</tr>\n";
}
?
>
</table>
<?php
}
else{
?
>
<p><b>There are no users in the system!</b></p>
<?php
}
?
>
</body>
</html>

  为了访问这个用户列表,在 index.php 文件中表单的上方添加一个到 users.php 的链接:

<p><a href='users.php'>see list of users</a></p>

 

  现在有了一个易于使用的用户名列表,每个用户名旁有一个 follow 链接。

  图 2. 用户列表 

  在进入下一个阶段之前,还需要编写一个小函数,该函数将返回当前用户正在追随的用户。这样一来,用户就可以用这个列表来确定是否追随另一个用户。

  回到 functions.php 文件,添加一个名为 following() 的函数,如清单 12 所示。将当前用户 ID 传递给该函数,就可以得到该用户正在追随的每个用户的 ID。

  清单 12. following() 函数

function following($userid){
    $users
= array();

    $sql
= "select distinct user_id from following
            where follower_id = '$userid'";
    $result = mysql_query($sql);

    
while($data = mysql_fetch_object($result)){
        array_push($users, $data
->user_id);

    }

    return $users;

}

  现在可以在 users.php 上运行这个函数,检查某个用户 ID 是否在该数组中。如果在,则使用 unfollow 链接。如果不在,则使用默认的 follow 链接。清单 13 显示修改后的代码。

0
相关文章