Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Search sql db alphebetically

  • 13-09-2005 09:13AM
    #1
    Registered Users, Registered Users 2 Posts: 648 ✭✭✭


    in SQL how do i search a colum by alpha.
    i dont want to order it i want to select only the rows with a TITLE field beginning with A for exmple

    Tnx


Comments

  • Closed Accounts Posts: 4,655 ✭✭✭Ph3n0m


    Basically your db query has to be like this


    SELECT * from table where TITLE LIKE '$letter%' order by TITLE ASC;

    Where you define $letter as which as A -> Z

    That select will select all items where Title is like "A....."

    As far as I remember, you do have to order your select (I havent tested the above select)


  • Registered Users, Registered Users 2 Posts: 648 ✭✭✭ChicoMendez


    hi tnx very much for that.

    ive one little question off that....

    If i want to create a dropdown list with the letters of the alphabet... but showing only the letters for which there is an entry in the db TITLE field beginning with that letter..

    How would i go about that.
    the drop down etc is ok... its the sql side that im not too sure about.

    tnx alot


  • Closed Accounts Posts: 4,655 ✭✭✭Ph3n0m


    Well you would basically do the same search but count the rows that are returned and the put that within a loop

    I was bored so I did a rough version for you


    To generate your dropdown list, use this code

    [PHP]<?
    echo "<select name='letter'>";
    foreach (range(A, Z) as $letter) {

    $sql_alpha = "SELECT * from table where title LIKE '$letter%'";
    $sql_alpha_check_result = mysql_query($sql_alpha) or die("Error checking database");
    $sql_alpha_check_count = mysql_numrows($sql_alpha_check_result);
    if ($sql_alpha_check_count == "0"){
    }
    else {
    echo "<option value='$letter'>$letter</option>";
    }
    }
    echo "</select>";
    ?>[/PHP]


  • Registered Users, Registered Users 2 Posts: 3,890 ✭✭✭cgarvey


    You can also do it with just one query which would be a bit more efficient as Ph3n0m's example...
    $sql_alpha = "SELECT DISTINCT LEFT( title, 1 ) ORDER BY title";
    

    .. will give you "A,C,D,H,T,S,Z" or whatever first letters are present in the column called title.

    .cg


Advertisement