while循环JOIN中的PHP SQL查询

时间:2013-10-18 16:13:30

标签: php mysql sql join while-loop

我正在为练习项目制作一个基本的通知系统。我有几张桌子,其中两张看起来如下:

> 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>";
                ?>

有更好的方法吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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注入的安全查询。 For more info