sql - Print data from a DB grouped under the starting letter using PHP? -


i'm trying set loop print data database table starts letter. example, let's usernames in database, want print every username starting letter "b". end result want achieve along lines of this:

a adam angel apple  b ball bear blue  c car cell chris  # 0wen 1uis 3than  .,_ .apple. ,car, _jeff_ 

i want able print usernames under corresponding character in start with. have starting characters under heading tags, need print usernames under them. figured running simple loop under each heading tag filters data trick, life of me can't figure out how go doing it. code far (i know print every user in table):

require_once 'important/connect.php'; $query = $link->prepare('select distinct usr info order usr'); $query->execute(); $users = $query->fetchall(pdo::fetch_obj); foreach ($users $user)  {     print "<center><a href=\"log.php?id={$user->usr}\" onclick=\"return popup(this.href)\">{$user->usr}</a></center>"; } 

this code above merely show i'm working with. i'm shooting keep each username print url well, when username clicked, display more information in seperate pop window, have working. anyway, how implement or way wanna go not possible?

as lelio faieta pointed out, looping through user list on , on again might bad performance. however, querying database on , on again might bad.

so suggest getting users once, , getting them in right order:

select usr info order usr group usr 

then loop through them, , keep track of starting letter you're on:

$oldletter = ''; $newletter = ''; foreach ($users $user)  {     $newletter = strtoupper(substr($user->usr, 0, 1));     if($oldletter != $newletter)     {         //we on new letter.         //print heading letters between old 1 , new one.         foreach(range(++$oldletter, $newletter) $letter)             print '<h2>' . $letter . '</h2>';         $oldletter = $newletter;      }      //print user, before.      print "<center><a href=\"log.php?id={$user->usr}\" onclick=\"return popup(this.href)\">{$user->usr}</a></center>"; } 

this not take care of last group (titled # in example) you. that, need check whether first character letter in sql , sort on somehow.

please note code not copy-paste-ready, need work on it. instance if old letter z there might problems. have not tested this, should before put production.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -