Skip to content
Advertisement

Duplication of results after selecting data from two tables with the same values

Good day! I’m having a problem in duplication of results when I’m selecting data from two tables with the same values. I have one data in my first table homepost with an ID of 2 and I have three data in table multiple with an ID of 2.

So. In my source code. I’m selecting all the data with the same values ID. But it duplicates my one data from homepost because I have three data from multiple with the same values [ID]. Any help? Thank you!

For example in the table below:

Table [homepost]                    Table [multiple]

homeID   homeDesc               multipleID     multipleImage
2          John                     2              Image1
3        Samantha                   2              Image2
                                    2              Image3
                                    3              Image4
                                    3              Image5

Results of my code:

John
Image1
John
Image2
John
Image3
Samantha
Image4
Samantha
Image5

What I want is:

John
Image1
Image2
Image3

Samantha
Image4
Image5

Here’s my Source Code:

<?php
    include ("dbconnect.php");

    $content_sql="SELECT post.postID, post.postTitle, post.postDesc, post.postImage 
                    FROM post 
                        JOIN category ON (post.categoryID=category.categoryID) 
                    WHERE post.categoryID=".$_GET['categoryID'];

    if($content_query=mysqli_query($con, $content_sql)) {
        $content_rs=mysqli_fetch_assoc($content_query);
    }

do {
    echo $content_rs['postTitle'];
    echo $content_rs['postDesc'];
} while ($content_rs=mysqli_fetch_assoc($content_query))

?>

Advertisement

Answer

You can simply check the name each time round the loop and only output it if its a new one

<?php
include ("dbconnect.php");

$sql="SELECT post.postID, post.postTitle, post.postDesc, post.postImage 
      FROM post 
          JOIN category ON (post.categoryID=category.categoryID) 
      WHERE post.categoryID=?";

$stmt = $con->prepare($sql);
$stmt->bind_param('i', $_GET['categoryID']);
$stmt->execute();

$result = $stmt->get_result();

$last_name = '';        
while ( $row = $result->fetch_assoc() ) {
    if ( $last_name != $row['postTitle'] ) {
        echo $row['postTitle'];
        $last_name = $row['postTitle'];
    }

    echo $row['postDesc'];
}
?>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement