2

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.

2 Answers 2

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I don't why I didn't do it before... really appreciate it!
0

'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"]; 

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.