Jump to content

Read all MySQL rows 'Username' and return all


woocha

Recommended Posts

Hi Guys..

 

  I need to read all of the rows from a MySQL table and return only the results that start with a user input letter.  So like if the user types in Andrew.  I want the database to return all rows that have usernames beginning with the letter a.

 

Has anyone ever done anything like this before?

 

Thanks :)

Thanks guys, but I am more worried about the SQL query...I mean If I use substr to finms the first letter of the name, how to I write the SQL to search all usernames that begin with that substring?  Is there an SQL function like

 $query = "SELECT username FROM users WHERE username starts with a";

?

 

I know it looks stupid, but is there anything like that?

try

<?php
$user_input = trim($_POST['name']);
$user_input = mysql_real_escape_string(substr($user_input,0,1));
$q = "SELECT GROUP_CONCAT(Username) as usernames FROM `users` Where username LIKE '".$user_input."%'";
$r = mysql_query($q) or die(mysql_error()."<br /><br />".$q);
print_r(mysql_fetch_assoc($r));
?>

$FirstLetter = $variable[0];

 

I can't give you the exact SQL but a guess is:

 

$query = "SELECT username FROM users WHERE username LIKE '" . $FirstLetter . "%'";

 

the above is probably rather wrong syntax-wise but you get the idea (please feel free to correct anyone).  Just use a LIKE statement, then the FirstLetter followed by a wildcard match. 

 

Rgds

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.