在循环中重复php

时间:2012-06-12 16:15:21

标签: php mysql while-loop

我从数据库中获取了一堆id - 对于每个id,我想做一个mysql查询来获取另一个表中的相关行。这工作正常,但我还需要为登录用户获取类似的数据。使用我正在使用的mysql查询 - 它根据最初提取的id的数量复制登录的用户数据。这是有道理的,虽然不是我想要的。我不想要登录用户的重复数据,我需要数据来自一个查询,所以我可以用时间戳订购。

<?php
    mysql_select_db($database_runner, $runner);
    $query_friends_status = "SELECT DISTINCT rel2 FROM friends WHERE rel1 = '" . $_SESSION    ['logged_in_user'] . "'";
    $friends_status = mysql_query($query_friends_status, $runner) or die(mysql_error());
    $totalRows_friends_status = mysql_num_rows($friends_status);

    while($row_friends_status = mysql_fetch_assoc($friends_status))
    {
        $friends_id = $row_friends_status['rel2'];
        mysql_select_db($database_runner, $runner);
        $query_activity = "SELECT * FROM activity WHERE user_id = '$friends_id' OR user_id = '" .  $_SESSION['logged_in_user'] . "' ORDER BY `timestamp` DESC LIMIT 15";
        $activity = mysql_query($query_activity, $runner) or die(mysql_error());
        $totalRows_activity = mysql_num_rows($activity);
        echo "stuff here";
    }
?>

3 个答案:

答案 0 :(得分:1)

您可以尝试此单个查询,看看它是否符合您的需要

$userID = $_SESSION['logged_in_user'];
"SELECT * FROM activity WHERE user_id IN (
    SELECT DISTINCT rel2 FROM friends 
    WHERE rel1 = '$userID')
OR user_id = '$userID' ORDER BY `timestamp` DESC LIMIT 15";

答案 1 :(得分:0)

你可能想要这样的东西:

  $user = $_SESSION['logged_in_user'];
  $query_friends_status = "SELECT * FROM friends, activity WHERE activity.user_id = friends.rel2 AND rel1 = '$user' ORDER BY `timestamp` DESC LIMIT 15";

您可以将*替换为您想要的字段,但请记住将表名放在字段名称之前,如:

table_name.field_name

我希望这会有所帮助。

答案 2 :(得分:0)

 <?php
    require_once "connect.php";

    $connect = @new mysqli($host, $db_user, $db_password, $db_name); 
    $result = $connect->query("SELECT p.name, p.user, p.pass, p.pass_date_change,p.email, p.pass_date_email, d.domain_name, d.domain_price, d.domain_end, d.serwer, d.staff, d.positioning, d.media FROM domains d LEFT JOIN persons p 
    ON d.id_person = p.id AND d.next_staff_id_person != p.id");

    if($result->num_rows > 1)
    {   
    while($row = $result->fetch_assoc())
    {

echo '<td class="box_small_admin" data-column="Imię i nazwisko"><div class="box_admin">'.$row["name"].'</div></td>';
echo '<td class="box_small_admin" data-column="Domena"><div class="box_admin">'.$row["domain_name"].'</div></td>';          
}}
?>