Jump to content

alphabetical mysql results?


Maverickb7

Recommended Posts

Hi, I was wondering if someone could point me in the right direction. I'm trying to have my mysql content listed on a single page in alphabetical with "A B C D E F ect.." at the top of the page. You click A and you'll get all items starting with A. Does anyone know of a tutorial I could use to learn how to do this?
Link to comment
https://forums.phpfreaks.com/topic/3734-alphabetical-mysql-results/
Share on other sites

[!--quoteo(post=350165:date=Feb 28 2006, 12:52 AM:name=Maverickb7)--][div class=\'quotetop\']QUOTE(Maverickb7 @ Feb 28 2006, 12:52 AM) [snapback]350165[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Hi, I was wondering if someone could point me in the right direction. I'm trying to have my mysql content listed on a single page in alphabetical with "A B C D E F ect.." at the top of the page. You click A and you'll get all items starting with A. Does anyone know of a tutorial I could use to learn how to do this?
[/quote]

Try using the sql code:
[code]SELECT *
FROM `your_table`
WHERE `name`
LIKE 'a%'
ORDER BY `name` ASC [/code]

you could pass in a variable for the letter you would like to sort by from a link.

so clicking on sort.php?letter=a would lead to:
[code]

$letter = $_GET['letter'];
$sql = 'SELECT * '
        . ' FROM `your_table` '
        . ' WHERE `name` LIKE  \'' . $letter . '%\''
        . ' ORDER BY `name` ASC';

$result = mysql_query($sql);

[/code]

hope that helps
  • 1 year later...
I think you meant that you want all values with a number at the beginning to start with a # sign, so basically, 7teen would be listed as #7teen?  Hmm...try this:

[code]<?php
$string = "7teen";
$first = substr($string, 0, 1);
if(is_numeric($first)) {
  $first = "#" . $first;
  $string = $first . substr($string, 1, strlen($string));
  }
echo $string;
?>[/code]

Hope this helps you out.

edit: all you have to do is read in your array in a foreach loop like this (I use an example array):

[code]<?php
$string_arr = array("123", "teen", "7teen", "HaLo2FrEeEk", "Alex", "4lex");
foreach($string_arr as $string) {
  $first = substr($string, 0, 1); // Gets the first character of the string
  if(is_numeric($first)) { // Checks to see if $first is a number
    $first = "#" . $first; // This would set $first to #7
    $string = $first . substr($string, 1, strlen($string)); // This appends the last characters to the new $first;
    }
  echo $string . "<br />";
  }
?>[/code]

This will output:

#123
teen
#7teen
HaLo2FrEeEk
Alex
#4lex

Since your query results are sorted already, the order won't be a problem.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.