This query outputs each result 6 times: So, for one row with a body of ‘ayo’, it will be outputted as: ayo
ayo
ayo
ayo
ayo
ayo
function get_comments($page_type, $spot) {
$query = mysql_query("
SELECT
comments.user_id AS user_id,
comments.page_type AS page_type,
comments.spot AS spot,
comments.comment AS comment,
comments.timestamp AS timestamp,
users.first_name AS first_name,
users.last_name AS last_name
FROM comments, users
WHERE page_type = '$page_type' AND spot = '$spot' AND (comments.user_id = users.user_id OR comments.user_id = '0')
ORDER BY timestamp DESC
");
while($fetch = mysql_fetch_assoc($query)) {
$comment = $fetch['comment'];
$timestamp = $fetch['timestamp'];
$timestamp_date = date('M d y\'', $timestamp);
$timestamp_time = date('g:m', $timestamp);
$comments_user_id = $fetch['user_id'];
if(date('H', $timestamp) > 12) {
$am_pm = 'pm';
} else {
$am_pm = 'am';
}
$first_name = $fetch['first_name'];
$last_name = $fetch['last_name'];
?>
<div id="replies">
<?php if($comments_user_id == '0') {echo 'Guest';} else { echo $first_name.' '.$last_name; } ?><br />
<?php echo $timestamp_date; ?><br />
<?php echo $comment; ?>
</div>
<?php
}
}
In here $page_type and $spot refer to: http://localhost/$page_type/$spot
You’re getting duplicates because your implicit join condition contains this:
and you have multiple rows with
comments.user_id = 0. Each of theseuser_id = 0rows will appear match your join condition and that will lead to duplicates. The solution is to fix your data so that each comment has a validuser_idwhere “valid” means “has an entry inusers” and the drop thecomments.user_id = 0part of your join condition. And while you’re at it, switch to InnoDB tables and add foreign keys to enforce this referential integrity constraint.BTW, if
user_idis an integer then you really shouldn’t be quoting it; you’re making the database do unnecessary work and building a bad habit that will cause you some pain and suffering if you every use another database. You should also switch to an explicit join: