November 14th, 2018, 03:40 AM
-
Grouping Duplicate Results
I need to group duplicate results so that the output is:
A, B, C etc.
The code I’m using that the moment is giving me:
AA, BBB, CC etc.
My database query returns the last ‘Distinct’ name, and I take the first letter of that and run it through my code so I understand why I’m getting duplicates because there are several Anthony, Bert, Connor, etc. in the ‘last’ name but when I run it through my code below I can’t seem to find a way to remove the duplicates.
I have tried multiple things such as array_unique but nothing seems to work as I keep getting the same result. I’d appreciate any help that I can get as I’m not the most experienced with PHP.
Thanks
[CODE]SELECT DISTINCT (last_name) FROM books GROUP BY last_name[CODE/]
[php]
<?PHP
do {
$str = $row_GetPeople['last_name'];
$first_letter = $str[0];
echo '<a href="results.php?id='.$first_letter.' ">'.$first_letter .'<a/><br>';
} while ($row_GetPeople = mysql_fetch_assoc($GetPeople)); ?>[php/]
November 14th, 2018, 03:51 AM
-
Sorry I can't see/find how I can edit this post to correct the / [php/]
November 14th, 2018, 09:22 AM
-
I think you have to have a number of posts before it will let you edit. However, a moderator can do it for you.
In any case you need to go back to the drawing board on this. You should not be using the decades old, deprecated mysql library. You need to switch to PDO or at least mysqli (PDO is better IMO). Your code will break if you upgrade to the latest version of PHP and in any case you have opened your web site to injection attacks. Once you have corrected that, come back with your new code if you have the same problem. In this case your problem may be related to using do-while instead of a simple while. The first time through your variables are uninitialized.
Last edited by gw1500se; November 14th, 2018 at 09:24 AM.
There are 10 kinds of people in the world. Those that understand binary and those that don't.
November 15th, 2018, 12:28 AM
-
Yes, editing only works for a short while after posting. But there isn't much code so no worries.
After you've fixed your code so that you're using PDO or mysqli, consider whether you might be able to make the query do more work than it is now...
November 15th, 2018, 04:46 PM
-
You should also have a look at you SQL query. Using both DISTINCT and GROUP BY is not needed in your case, you can just pick one of them.
November 22nd, 2018, 03:21 AM
-
Thanks to everyone for all the feedback.
So far I have managed to connect using mysqli and ran a if (mysqli_num_rows($result) > 0) { query with everything working out.
I need to look into arrays/implode/explode now I think to get back to my original problem.
Thanks again.