1

我正在为一个练习项目制作一个基本的通知系统。我有几个表,其中两个如下所示:

> Table 1: "Users"
> 
userid | username  | Firstname | Lastname  
1      | Daffy     |   Daffy   | Duck
2      | Flinstone |   Fred    | Flinstone 
3      | dduck     |   Donald  | Duck
> 
> Table 2: "Notifications"
> 
 Notification_id | from_user_id | to_user_id | SeenOrUnseen | type    
     1           |   1          |     2      |       1      |  fRequest               
>    2           |   1          |     2      |       0      |  comment               
>    3           |   1          |     2      |       1      |  comment               
>    4           |   3          |     1      |       1      |  fRequest               
>    5           |   2          |     3      |       1      |  fRequest               
>    6           |   2          |     3      |       0      |  comment               
>    7           |   3          |     2      |       0      |  comment

然后我需要来自这两个表的数据,并且通常会在发送 sql 查询之前加入 user_id 和 from_user_id 上的表。但是,连接似乎返回多个值,因为在第二个表中有多个 from_user_id 实例。相反,我正在查询数据库,在 while 循环中返回数据,并在该 while 循环中向数据库发送另一个查询以获取不同表的信息:

include('../../db_login.php');
$con = mysqli_connect("$host", "$username", "$password", "$db_name");
$tbl_name = "Profile";
$tplname = "profile_template.php";
$tplname2 = "public_profile_template.php";
$myid = $_SESSION['identification'];
//CHECK CONNECTION
if(mysqli_connect_errno($con))  {
echo "failed to connect" . mysql_connect_error();
}else {
$result = mysqli_query($con, "SELECT * FROM Notifications WHERE to_user_id='$myid'");
$count = mysqli_num_rows($result);
if($count == 0){

    $style = "display:none;";
} else {

echo "<ul class='notifications'>";
    while($row = mysqli_fetch_array($result)){
    $from_user_id = $row['from_user_id'];
    $to_user_id = $row['to_user_id'];
    $seen = $row['seen'];
    $nature = $row['nature'];
        $result2 = mysqli_query($con, "SELECT * FROM users WHERE id='$from_user_id'");
        $count2 = mysqli_num_rows($result2);
        if($count2 != 0){
        while($row2 = mysqli_fetch_array($result2)){
        $fromFirstname = $row2['Firstname'];
        $fromLastname = $row2['Lastname'];

        }
    if($nature == 'fRequest'){
    echo "<li> You have received a friend request from" . $fromFirstname . " " . $fromLastname . "</li>";
    }
    }

    }   
    echo "</ul>";
}


mysqli_close($con);
}
                echo "<div id='NoNotification'></div>";
                echo "<div id='Notification' style='" . $style . "'></div>";
                ?>

有没有更好的方法来做到这一点?

谢谢你的帮助!

4

1 回答 1

1

你可以这样做:

SELECT n.*, u.*
FROM Notifications n 
JOIN users u ON n.from_user_id=u.id
WHERE n.to_user_id=$myid
ORDER BY n.id, u.id

您将获得所需的所有数据。通知数据和用户数据。最好定义您要检索的字段,而不是*这样您就可以更好地了解您使用的内容以及不发送您不使用的数据。

你使用整数(id)作为字符串,你可以把它放在$myid那里。还要注意这不是 MySQL 注入的安全查询。欲了解更多信息

于 2013-10-18T16:20:24.737 回答