I'm having a hard time wording this question. I have a database of messages and I want to retrieve, for example, the latest 2 from each conversation. How can I put a limit inside the query syntax to limit each unique user to just two? Or do I have to select all and then loop inside the fetch assoc? The query looks something like this:
$to = $_REQUEST['to'];
$lastid = $_REQUEST['lastId'];
$link = mysqli_connect('localhost', 'root', '', 'messagedb');
if ($link) {
$query = mysqli_query($link, "SELECT * FROM messages WHERE (toName='$to' OR fromName='$to') AND id>'$lastid' order by id desc");
$messages = array();
while ($row = mysqli_fetch_assoc($query)) {
if (!in_array($row['toName'], $messages) || !in_array($row['fromName'], $messages)) {
$messages[] = $row;
}
}
}
Of course that's not working...it just gets everything back...plus I can't put a limit on how many rows already in there. I'm hoping there's a simple solutions for the query. Thanks in advance!
The database looks something like this:
id | fromName | toName | theMessage
------------------------------------------------------------
1 me joe some message to joe from me
2 john me message from john to me
3 sarah me message from sarah to me
4 joe me answer back to joe from me
5 me john answer back to john from me
6 me sarah answer back to sarah from me
//and so on...just conversations between people
So in my query, the $to is me, or whatever user will be using it. I want to get my/their conversations with each person but limit it to a certain number at the start...so later they can load more.