I'm sure others have been curious about this so I thought I would post it.
This class takes a table name and a column producing an alphabet navigation bar that links letters where there are records that begin with that letter. <- bad grammar
I don't work particularly hard for this company so I am sure that this class could see a lot of improvement.
Code: Select all
class AbcBar
{
public $Chars = array();
public $Alphabet = array();
public $TableName;
public $ColumnName;
public function __construct($table_name, $column_name)
{
$this->TableName = $table_name;
$this->ColumnName = $column_name;
$this->GetChars();
$this->PopulateAlphabetArray();
}
private function GetChars()
{
$sql = "SELECT DISTINCT LEFT(`{$this->ColumnName}`, 1) as first_letter FROM `{$this->TableName}`";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result))
{
$this->Chars[] = strtoupper($row[0]);
}
}
private function PopulateAlphabetArray()
{
$this->Alphabet = range("a", "z");
}
public function CreateAlphabetNavigationBar()
{
foreach ($this->Alphabet as $letter)
{
if (in_array(letter, $this->Chars))
{
$navi[] = '<a href="?letter='.$letter.'" title="Sort links by the letter '.$letter.'">'.$letter.'</a>';
}
else
{
$navi[] = $letter;
}
}
echo implode(" | ", $navi);
}
}
mysql_connect('localhost', 'adfasdfasdfasdfasdfasdffasdffasdfasdf', 'safsdfadsdfasdfasdfasfdas');
mysql_select_db('test');
$abc = new AbcBar('links', 'name');
$abc->CreateAlphabetNavigationBar();EDIT: Made one small improvement, removing the RemoveDuplicateChars() function, which made sure the array only contained unique chars, in favor of using the SQL DISTINCT keyword.
EDIT2: Added JayBird's suggestions.