简体   繁体   中英

Select name from database by first character only

I want to be able to find all the names in a database by its first character. For example:

$sql="SELECT name LEFT(".$_GET['abc'].",1) from `users` ORDER BY `id` LIMIT 20";
$res=mysql_query($sql) or die(mysql_error());

And output:

Letter: C

Names: Craig, Chris, Chad, etc.

I feel as if it's simple and for some reason I can't find it on Google. I also don't want to use LIKE , as I need it to be only the first character.

use this :

SELECT name FROM `users` WHERE name LIKE 'c%'

% is the "joker" in SQL... with most DBMS

You query need to be changed a bit:

$first_letter = substr($_GET['abc'], 0, 1);
$sql="SELECT name from `users` WHERE LEFT(name ,1) = '" . $first_letter . "' ORDER BY `id` LIMIT 20";
// OR SUBSTR variant
$sql="SELECT name from `users` WHERE SUBSTR(name, 1, 1) = '" . $first_letter . "' ORDER BY `id` LIMIT 20";
$res=mysql_query($sql) or die(mysql_error());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM