Aditya Raj
Aditya Raj

Reputation: 168

PHP - Get data from database then fetch it again

I am trying to get data from database then fetch it again with different mysql_query using while() in both query , but the problem it is producing results more than one time because i used while in first query . So any answer to get all data without while() for first query ?

$AllFrnd = "SELECT friend , followers FROM frndlist WHERE userid = '".$_SESSION[' user_id ']."' ORDER BY id DESC";
$getfrnd = mysql_query($AllFrnd);
while($frnd = mysql_fetch_array($getfrnd)) {
    $query2 = "SELECT * FROM post WHERE (userid ='".$frnd['friend']."') OR (userid =       '".$frnd['followers']."') OR (userid = '".$_SESSION[' user_id ']."') ORDER BY id DESC";
    $rs = mysql_query($query2);
    while($row = mysql_fetch_array($rs)) {
        echo ''.$row['content'].'';

Upvotes: 0

Views: 162

Answers (3)

vural
vural

Reputation: 391

You can use a query just like this :

SELECT *
FROM post
WHERE userid IN (
    SELECT followers
    FROM frndlist
    WHERE userid = '" . $_SESSION['user_id'] . "'
)
OR userid IN (
    SELECT friend
    FROM frndlist
    WHERE userid = '" . $_SESSION['user_id'] . "'
)
OR userid = '" . $_SESSION['user_id'] . "'
ORDER BY id DESC

Upvotes: 1

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

You can easyly handle by using this function

function sel($table,$field="*", $condition="1",$sort="" ){
    if($sort!='') $sort="order by $sort ";
    //echo "select $field  from $table where $condition $sort ";
    $sel_query=mysql_query("select $field  from $table where $condition $sort ");
    //$sel_result=array();
    while($temp_res=@mysql_fetch_array($sel_query))
    {
        $sel_result[]=$temp_res;
    }
    return isset($sel_result)?$sel_result: 0;
}


while($frnd = mysql_fetch_array($getfrnd)) {
    $temp_res=sel("post","*"," (userid ='".$frnd['friend']."') OR (userid =       '".$frnd['followers']."') OR (userid = '".$_SESSION[' user_id ']."') ORDER BY id DESC");
    if($temp_res)foreach($temp_res as $row){
        echo $row['content'];
    }
}

Upvotes: 0

Jenis Patel
Jenis Patel

Reputation: 1615

you can try this :

// Associative array

   $frnd =mysql_fetch_array($getfrnd,MYSQL_ASSOC);

then get your data as like :

echo $frnd ["friend"]
echo $frnd ["followers"]

And you should use mysqli_fetch_array instead of mysql_fetch_array

Hope it helps

Upvotes: 2

Related Questions