• 0

[PHP/MySQL] How to query first letter of name


Question

Hey Guys,

I'm looking to try to query MySQL data (in peticular names) by the first letter of the string.

Anyone know how I might go about doing this?

Thanks!

-Ax

Link to comment
Share on other sites

10 answers to this question

Recommended Posts

  • 0

Do you mean SORT by fname?

SELECT * FROM my_table ORDER BY field_name ASC

You can replace ASC with DESC for deaccesding (sp.).

so that will gets you the fields in alphabetic order.. ascending or deascending if you use DESC instead of ASC.

Link to comment
Share on other sites

  • 0

But will that work with a MySQL Query?

e.g.

SELECT * FROM table_name WHERE name="First letter of string"

Where the query will return all names that start with A or B, etc.

-Ax

Link to comment
Share on other sites

  • 0

But will that work with a MySQL Query?

e.g.

SELECT * FROM table_name WHERE name="First letter of string"

Where the query will return all names that start with A or B, etc.

-Ax

woops.. well my other post doesnt make revelance after I posted it before I saw your post.. I think you can use wildcards tho..

select * FROM my_table WHERE field=a%

Link to comment
Share on other sites

  • 0

I was able to accomplish this by using the LIKE operator.

Here's the final query:

SELECT * FROM stuvote_students WHERE last LIKE 'a%'

Thanks for all the help!

-Ax

Link to comment
Share on other sites

  • 0

I was able to accomplish this by using the LIKE operator.

Here's the final query:

SELECT * FROM stuvote_students WHERE last LIKE 'a%'

Thanks for all the help!

-Ax

That's fine if you are just looking for the first lette in the field beginning with a. I am still scracthing my head as to how to get this to search by first letter. Ie if I want to return everyone starting with B or maybe V etc.

Using following to set up list:

for ($i="A"; $i != "AA"; $i++) echo "<a href=\"view.php\"> $i: </a>";

I thought that following might work:

$s_query="SELECT * FROM table where name LIKE '$i%' ";

But Nah. i think it is because the default $i is AA.

Any thoughts?

Ian

Link to comment
Share on other sites

  • 0

All sorted now:

Went back to first principles and it really was quite simple.

Set up navigation as follows:

for ($i="A"; $i != "AA"; $i++) echo "<a href=\"page.php?field=$i\"> $i  </a>";

$i=$_REQUEST['field'];

$query = "SELECT * FROM table where field LIKE '$i%' ";

When page opens there is a list of companies then is linked back to itself.

Don't know why I didn't think of this earlier!!

Ian

Link to comment
Share on other sites

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

    • No registered users viewing this page.