• 0

[sql] get first letter of a result


Question

I have a list of members in my database.

I would like to make a list of links at the top of a page containing the first letter of the members first name but only make the links appear if there is a particular member that has that last name.

I came up with this

$surname_query = "SELECT DISTINCT last_name FROM members ORDER BY last_name";
   $getlist = mysql_query($surname_query) or die(mysql_error());

   while ($row = mysql_fetch_array($getlist)) {

	   $surname = substr($row['last_name'], 0, 1);
	   echo "<a href='?lname=$surname' title='Surname´s beginning with $surname'>$surname</a> ";

   }

Problem is it makes a seperate link for each surname it finds, so if there is a member with the surname Stewart and another with Sausages the code returns two links for the letter S.

Is there any way of making the query only return a letter once or any other way anyone can think of to do this?

Link to comment
https://www.neowin.net/forum/topic/618171-sql-get-first-letter-of-a-result/
Share on other sites

8 answers to this question

Recommended Posts

  • 0

Personally, I would add the results to an array then output that.

Example:-

<?php
$dbQuery = "SELECT DISTINCT last_name FROM members ORDER BY last_name";
$dbResult = mysql_query($dbQuery) or die(mysql_error());
$surnameArray = array();
while ($row = mysql_fetch_array($dbResult))
{
	   $surname = substr($row['last_name'], 0, 1);
	   if(!in_array($surnameArray))
	   {
	   	$surnameArray[] = $surname;
	   }
}
foreach ($surnameArray as $surnameValue) 
{
	echo "<a href='?lname=$surnameValue' title='Surname´s beginning with $surnameValue'>$surnameValue</a> ";
}
?>

Although, as njlouch suggests, it would be alot easier to only bring back DISTINCT first letters with your SQL query to avoid 2 PHP loops.

SilverB. ;)

  • 0

Hmmm, sounds like it should work but I'm getting a error saying Undefined index: last_name and if I try your code SilverBullet I'm told Wrong parameter count for in_array()

  • 0

Ooops, Sorry bud.

Try:-

<?php
$dbQuery = "SELECT DISTINCT last_name FROM members ORDER BY last_name";
$dbResult = mysql_query($dbQuery) or die(mysql_error());
$surnameArray = array();
while ($row = mysql_fetch_array($dbResult))
{
	   $surname = substr($row['last_name'], 0, 1);
	   if(!in_array($surname,$surnameArray))
	   {
		   $surnameArray[] = $surname;
	   }
}
foreach ($surnameArray as $surnameValue)
{
	echo "<a href='?lname=$surnameValue' title='Surname´s beginning with $surnameValue'>$surnameValue</a> ";
}
?>

Noob mistake.... :blush:

Dev's SQL query works for me BTW.

Another SQL example:-

SELECT DISTINCT LEFT(`name`,1) FROM `user_users`

  • 0
Ooops, Sorry bud.

Try:-

<?php
 $dbQuery = "SELECT DISTINCT last_name FROM members ORDER BY last_name";
 $dbResult = mysql_query($dbQuery) or die(mysql_error());
 $surnameArray = array();
 while ($row = mysql_fetch_array($dbResult))
 {
		$surname = substr($row['last_name'], 0, 1);
		if(!in_array($surname,$surnameArray))
		{
			$surnameArray[] = $surname;
		}
 }
 foreach ($surnameArray as $surnameValue)
 {
	 echo "<a href='?lname=$surnameValue' title='Surname´s beginning with $surnameValue'>$surnameValue</a> ";
 }
 ?>

Noob mistake.... :blush:

Dev's SQL query works for me BTW.

Another SQL example:-

SELECT DISTINCT LEFT(`name`,1) FROM `user_users`

Thanks, worked perfectly. (Y)
SELECT last_name = DISTINCT LEFT(last_name,1) FROM members ORDER BY last_name
Thanks for trying but that doesn't seem to work either.
  • 0

 SELECT DISTINCT LEFT(lastname,1) AS LastInitial FROM members ORDER BY LastInitial ASC

<?php
 $dbQuery = "SELECT DISTINCT LEFT(lastname,1) AS LastInitial FROM members ORDER BY LastInitial ASC";
 $dbResult = mysql_query($dbQuery) or die(mysql_error());
 while ($row = mysql_fetch_array($dbResult))
 {
	   echo "<a href='?lname=$LastInitial' title='Surname´s beginning with $LastInitial'>$LastInitial</a> ";
 }
 ?>

This is much more efficient in every way. Try to think about how you can slim the dataset to being as small and efficient as it can possibly be before the application code starts in on it's functions. This will make/keep your apps running exponentially faster as the DB apps are generally much faster than application code.

That, and why pass around more data than you'll actually use?

Edited by Josh
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • The memory and nvme can be swapped and upgraded with standard parts. But the GPU cannot, which is the weakest part of the box. It's a dead product at these prices.
    • Sounds like the debloated build you are running is missing some components that the Photos app and Snipping Tool rely on.
    • Apparently, Microsoft doesn't use water in their taps, washrooms or clean their facility. /sarc
    • Wow, throwback.  VERY VERY briefly - but realised that it wasn't the language I needed for the tasks I was taking on.
    • Apple and Tesla trade secrets reportedly exposed following a Tata Electronics cyberattack by Hamid Ganji Image via Depositphotos.com Tata Electronics has confirmed that it detected a cybersecurity incident in some of its systems. The Indian company is a manufacturing partner of both Apple and Tesla, and the incident may have exposed some trade secrets belonging to the two American companies. The World Leaks ransomware group is said to be behind the attack, and it has reportedly posted up to 200,000 files on the dark web, including component designs and specification documents related to Apple and Tesla products. Tata Electronics told Reuters that its response protocols were deployed immediately and that the “incident has had no impact on our operations across businesses, which remain unaffected.” The ransomware group reportedly sent a ransom demand to Tata Electronics, while Apple has launched an investigation into the incident. World Leaks claims it stole more than 200,000 files totaling over 630GB from Tata Electronics. Some database files on the ransomware group’s website are titled "com.apple.factorydata," which could refer to Apple’s iPhone production operations in India. Moreover, some documents reportedly contain material specifications and quality inspection standards for iPhone circuit board components. However, Apple is not the only affected company. A folder found in the World Leaks database is titled "NV36 Chargeport Controller - North America," which may refer to Tesla Model Y components. Additionally, other files in the database reportedly contain drawings related to Tesla’s Project Highland, the internal codename for the EV maker’s updated Model 3 sedan. To support the authenticity of the stolen files, World Leaks has published documents containing footers that read: "This document contains proprietary and confidential information of Apple Inc." and "information contained herein is deemed confidential, proprietary, and a trade secret of Tesla Inc." Cybersecurity researcher Rajshekhar Rajaharia told Reuters that the database also contains emails, event logs spanning several years, and passport copies of employees, including foreign nationals. Both Tesla and Apple have declined to comment on the scale of the incident.
  • Recent Achievements

    • One Month Later
      nates earned a badge
      One Month Later
    • Week One Done
      Almohandis earned a badge
      Week One Done
    • Rookie
      dorf went up a rank
      Rookie
    • First Post
      mike_rumble earned a badge
      First Post
    • Dedicated
      tuben earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      483
    2. 2
      +Edouard
      200
    3. 3
      PsYcHoKiLLa
      96
    4. 4
      Michael Scrip
      91
    5. 5
      neufuse
      71
  • Tell a friend

    Love Neowin? Tell a friend!