Mat
Mat

Reputation: 6324

How to get multiple results from SQL query

I have this function:

function findAllmessageSender(){
$all_from =  mysql_query("SELECT DISTINCT `from_id`  FROM chat");
$names = array();
while ($row = mysql_fetch_array($all_from)) {
$names[] = $row[0];
}
return($names);
}

that returns all the ID of my users in a private messaging system. Then I want to get the all the messages where the user_id is equal to the user logged in and from_id is equal to all from_id I got from the previous function:

 function fetchAllMessages($user_id){
 $from_id = array();
 $from_id = findAllmessageSender();
 $data = '\'' . implode('\', \'', $from_id) . '\'';
 //if I echo out $ data I get these numbers '113', '141', '109', '111' and that's what I want
 $q=array();
$q = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id`   IN($data)") or die(mysql_error());
 $try = mysql_fetch_assoc($q);
 print_r($try);
 }

print_r return only 1 result:

Array ( 
[id] => 3505 
[from_id] => 111 
[to_id] => 109 
[message] => how are you? 
[sent] => 1343109753 
[recd] => 1 
[system_message] => no 
)

But there should be 4 messages.

Upvotes: 2

Views: 3191

Answers (2)

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

'mysql_fetch_assoc' returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.

You need to iterate array like:

        while ($row = mysql_fetch_assoc($q)) {      
           echo $row["message"]; 

}

Upvotes: 0

SameOldNick
SameOldNick

Reputation: 2457

You have to call mysql_fetch_assoc() for each row that is returned. If you just call mysql_fetch_assoc() once then its only going to return the first row.

Try something like this:

$result = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id`   IN($data)") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
    print_r($row);
}

Upvotes: 4

Related Questions