<?php
class Search_By_Name
{
const FIRST = 1 ;
const LAST = 2 ;
protected static $db ;
protected static $mode ;
protected static $letter ;
protected static $results ;
public function __construct( $letter, $db, $mode = SEARCH_BY_NAME::LAST )
{
self::$db = $db;
self::$mode = $mode ;
self::$letter = $letter ;
self::$results = array( );
if( $db )
{
/**
* I'll assume:
* id - integer identifier
* name - varchar / text name
* table - the table name that you wanna search
*/
if( ( $result = mysql_query( "SELECT name,id FROM `table`", self::$db ) ) )
{
if( mysql_num_rows( $result ) )
{
while( $row = mysql_fetch_assoc( $result ) )
{
if( self::match( $row['name'] ) )
{
self::$results[]=$row['id'];
}
}
}
mysql_free_result( $result );
}
else die( sprintf( "Failed to query MySQL database: %s", mysql_error( self::$db ) ) );
}
else die( sprintf( "The database variable passed to %s is invalid.", __METHOD__ ) );
}
public function next( )
{
if( self::results( ) and ( $id = array_shift( self::$results ) ) )
{
/**
* I'll assume:
* id - integer identifier
* table - the table name that you wanna search
*/
if( ( $query = mysql_query( sprintf(
"SELECT * FROM `table` WHERE `id` = '%d' LIMIT 1",
$id
), self::$db ) ) )
{
if( mysql_num_rows( $query ) )
{
return mysql_fetch_assoc( $query );
}
}
}
else return null ;
}
public function results( )
{
if( count( self::$results ) )
{
return true;
}
}
protected function match( $string )
{
$name = array(
'first' => current( explode( ' ', $string ) ),
'last' => end( explode( ' ', $string ) )
);
if( $name['first'] and $name['last'] )
{
switch( self::$mode )
{
case SEARCH_BY_NAME::FIRST:
return ( strtolower( substr( $name['first'], 0, 1 ) ) == strtolower( self::$letter ) );
break;
case SEARCH_BY_NAME::LAST:
return ( strtolower( substr( $name['last'], 0, 1 ) ) == strtolower( self::$letter ) );
break;
}
}
}
}
/**
* Connecting to the database, you shouldn't need to do this ...
*/
$db = mysql_connect( "localhost", "root", "" );
/**
* Selecting database ^^ dito ....
*/
if( mysql_select_db( "names", $db ) )
{
/**
* Search for last names beginning with a b
*/
$search = new Search_By_Name( 'b', $db );
/**
* Check there is results to use
*/
if( $search->results( ) )
{
/**
* Loop through each result $next is an assoc array of all data in table
*/
while( $next = $search->next( ) )
{
echo "<pre>";
print_R( $next );
echo "</pre>";
}
}
else echo "no results\r\n";
}
?>