admin

如何从SQL查询中获取多个结果

sql

我有这个功能:

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);
}

该消息将在私人消息传递系统中返回我的用户的所有ID。然后,我想获得所有消息,其中user_id等于登录的用户,并且from_id等于from_id从上一个函数获得的所有消息:

 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仅返回1个结果:

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

但是应该有4条消息。


阅读 160

收藏
2021-06-07

共1个答案

admin

您必须调用mysql_fetch_assoc()返回的每一行。如果您只调用mysql_fetch_assoc()一次,那么它只会返回第一行。

尝试这样的事情:

$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);
}
2021-06-07