Assuming the code lines tally, the sql spitting out is:
$query="select sender, buddy, message from chatdata where sender = '<font color=red>$username</font>' or sender like '%$buddy%' and buddy ='<font color=blue>$buddy</font>' or buddy like '%$username%' order by id desc";
Try formatting it with parentheses:
$query="SELECT sender, buddy, message FROM chatdata WHERE ((sender = '<font color=red>$username</font>' or sender like '%$buddy%') and (buddy ='<font color=blue>$buddy</font>' or buddy like '%$username%')) ORDER BY id DESC";
No guarantees ;-)