skip to Main Content

Im trying to make a php message script i can output the message’s but im having a issue with grouping them

But im outputting the message’s and if the same person sends 2 message’s it shows has separate

I can ether just output all the from usernames on the left side then when the user clicks a chat head the messege will do a simple search where that username but again it will show muti chat heads for the same users

$stmt2m2 = $db->prepare('SELECT * 
                        FROM messages 
                        WHERE recipient_username = ? 
                        LIMIT  4 ');
$stmt2m2->execute( array($_SESSION['username'] ) ) ;
$row2m2 = $stmt2m2->fetchAll();
                                
foreach($row2m2 as $users2) {   
?>
    <a href="#" class="media">
        <div class="item-img">
            <img src="media/figure/notifiy_1.png" alt="Notify">
        </div>
        <div class="media-body">
            <h6 class="item-title"><?php echo $users2['sender_username'] ;  ?></h6>
            <div class="item-time"><?php echo $users2['date'] ;  ?></div>
            <p><?php echo $users2['message'] ;  ?></p>
        </div>
    </a>
                                            
<?php  
} 
?>

2

Answers


  1. Chosen as BEST ANSWER
            $stmt2m2 = $db->prepare('SELECT DISTINCT sender_username  FROM messages WHERE recipient_username = ? LIMIT  4  ');
    $stmt2m2->execute( array($_SESSION['username'] ) ) ;
    $row2m2 = $stmt2m2->fetchAll();
                                
             foreach($row2m2 as $users2)
                            {   
    
    }
    

  2. First you have to group the data user wise (Best approach is to use userid instead of username to group the data) using a foreach loop like this :

    $row2m2 = array();

    foreach($userData as $users) 
    { 
        $row2m2[$users['sender_username']][] = $users; 
    }
    

    Then you have to print it as following :

    <?php
    foreach($row2m2 as $users223) 
    {  ?>
        <a href="#" class="media">
            <div class="item-img">
                <img src="media/figure/notifiy_1.png" alt="Notify">
            </div>
            
                <h6 class="item-title"><?php echo $users223[0]['sender_username'] ;  ?> </h6>
                <div class="item-time"><?php echo $users223[0]['date'] ;  ?></div>
        </a>
        <?php
            foreach($users223 as $users2)
            { ?>
                <div class="media-body">
                    <p><?php echo $users2['message'] ;  ?></p>
                </div>                          
            <?php  
            } 
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search