• 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

    • How can it beat a Steam machine without a serious GPU? The two CU iGPU only provides about 5fps in gaming. That's not going to make any gamer happy.
    • Anthropic introduces Claude Tag, a new AI teammate for Slack by Fiza Ali Anthropic has announced Claude Tag, a new feature that lets teams work with Claude directly inside Slack. The idea is simple: once Claude is added to a Slack workspace and given access to selected channels, users can tag @Claude in conversations and assign tasks. Claude can then work through those requests using connected tools and data sources before posting its results back into a Slack thread. What makes Claude Tag different from a typical chatbot is that it's designed to operate as a shared assistant for an entire team rather than a single user. Everyone in a channel interacts with the same Claude instance. This allows the team members to see ongoing work and continue tasks started by others. Furthermore, Anthropic says the AI can build context over time by following conversations in channels where it has permission to operate. This means users don't have to repeatedly provide the same background information for every request. The system is also designed for asynchronous work. Instead of waiting for responses in a chat window, users can assign a task to Claude and return later once the work is complete. Anthropic says Claude can break larger requests into multiple steps and use connected tools to complete them. Moreover, the system can also schedule follow-up tasks and continue working on projects over extended periods. Another feature allows Claude to keep the users updated and follow up on unresolved tasks when its optional "ambient" mode is enabled. The company says the tool is already being used internally for software development, data analysis, support workflows, and debugging. According to Anthropic, around 65% of its product team's code is now generated through its internal version of Claude Tag. For organisations concerned about security, administrators can control which channels, tools, and data sources Claude can access. Separate Claude instances can also be configured for different departments, helping keep information isolated between teams. Administrators can also monitor activity logs, review completed tasks, and set spending limits at both the organisation and channel level. Claude Tag is now available in beta for Claude Enterprise and Claude Team customers and runs on Claude Opus 4.8 that was announced this May. The feature will also replace Anthropic's existing Claude in Slack application, with current users able to migrate within a 30-day migration window. Lastly, eligible customers will receive introductory credits to help teams evaluate the new experience.
    • Beats Studio Pro wireless over-ear ANC headphones drop to their lowest price yet by Fiza Ali Amazon is currently offering the Beats Studio Pro headphones at their all-time low price. The Studio Pro use 40mm active drivers which are designed to improve clarity and reduce distortion compared to previous models, with up to an 80% improvement over the Beats Studio3 Wireless. A built-in digital processor adjusts frequency response to keep the sound balanced rather than overly boosted in any one area. They also include Active Noise Cancelling that adapts to your surroundings to reduce background noise along with a Transparency mode that lets outside sound in when you need awareness of what’s going on around you. Furthermore, the headphones support personalised Spatial Audio with dynamic head tracking as well as Dolby Atmos playback on supported content. Moreover, built-in voice-targeting microphones improve call quality. You can also switch between three sound profiles including Beats Signature for balanced music playback, Entertainment for films and gaming, and Conversation for clearer voice in calls and podcasts. Physically, they are designed to be worn for long periods without feeling heavy or awkward. The ear cushions use UltraPlush engineered leather while metal sliders allow you to adjust the fit. On the connectivity side, the Studio Pro use Class 1 Bluetooth for a stable, long-range wireless connection. There is also a 3.5mm input if you want to plug in directly, including use with in-flight entertainment systems. Controls are located on the headphones and include a "b" button for music and call control, a volume rocker, and a multifunction button used for switching listening modes, EQ settings, power, and pairing. In addition, the headphones offer integration with both Apple and Android devices. On Apple devices, they support one-touch pairing with iCloud-linked devices, hands-free Siri access, Find My tracking based on last connected location, and automatic software updates. On Android devices, they support Google Fast Pair, Audio Switch between compatible devices, and Google Find My Device tracking, with additional features available through the Beats app. When it comes to the battery performance, it is rated at up to 40 hours of listening time with ANC turned off, and up to 24 hours with ANC or Transparency mode enabled. A 10-minute Fast Fuel charge should provide up to 4 hours of playback. Finally, the headphones use a rechargeable lithium-ion battery and charge via USB-C. Beats Studio Pro Wireless Over-Ear ANC Headphones: $149.95 (Amazon US) Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
    • "lets you pause updates by choosing an end date, for up to 35 days" Wasn't it "indefinitely"?
    • Those extra reboots are related to the UEFI Secure Boot certificate update thing.
  • Recent Achievements

    • Rookie
      DaviKar went up a rank
      Rookie
    • Dedicated
      HidekoYamamoto94 earned a badge
      Dedicated
    • One Month Later
      timbobit earned a badge
      One Month Later
    • One Month Later
      nates earned a badge
      One Month Later
    • Week One Done
      Almohandis earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      460
    2. 2
      +Edouard
      161
    3. 3
      PsYcHoKiLLa
      110
    4. 4
      Michael Scrip
      81
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!