PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 9, 2022

[FIXED] How do I limit this to exclude duplicates? I'm seeing my message twice because I'm friends with more than one person

 July 09, 2022     mysql, php, posts     No comments   

Issue

Question: Can someone help me fix the following piece of code to meet the following info:

When using this query, it sees that my username is in the database multiple times on diff columns, and so it is duplicating my posts when finding them in the query. I WANT it to show posts at diff timestamps by the same person, but not display from the same person if timestamp is the same.

Might be a better way to code the query, if so, I wouldn't mind seeing those options. Would doing a UNION query be the best way to do this?

$query = "SELECT p.* ".
"FROM posts p ".
"INNER JOIN friendships f ON p.username = f.user2 OR p.username = f.user1 ".
"WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' ORDER BY id DESC"; 

SOLUTION:

I am answering my own question here, just to give someone a workable solution from what I did to fix the issue. I tried grouping by ID and then turning around and ordering by ID; however, it threw an error -- so instead I am ordering by timestamp, and grouping by ID. Below is my code. Worked for me -- and hopefully this ends up helping someone else!

$query = "SELECT p.*, MAX(timestamp) AS latest ".
"FROM posts p ".
"INNER JOIN friendships f ON p.username = f.user2 OR p.username = f.user1 ".
"WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' GROUP BY id ORDER BY  latest DESC";   

Solution

Use GROUP BY to tell mysql what entity/fields you want to be unique:

SELECT p.*
FROM posts p
INNER JOIN friendships f ON (p.username = f.user2 OR p.username = f.user1)
WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' 
GROUP BY posts.id
ORDER BY id DESC


Answered By - Puggan Se
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing