i'm PHP Programmer and i'm Here to Help PHP developers with php coding




Basic DB Search Script

PHP Tutorial With MYSQL Coding
<?php
/**
 * @author Bradley Weston <admin@webod.co.uk>
 */


if(version_compare(PHP_VERSION, 5, '<'))
    die("Please upgrade your PHP.");
if(!class_exists('mysqli'))
    die("Please install Mysqli extention.");


class DB_Search {

    protected $DB = NULL;
    protected $Keywords = NULL;
    protected $searchTable = NULL;
    protected $searchColumns = NULL;
    protected $lastSearchResult = NULL;

    function __construct (){
        $this->Keywords = array();
        $this->searchColumns = array();
    }

    function setSearchTable ($Tablename){
        $this->searchTable = $Tablename;
    }

    function addSearchColumn ($Columnname){
        $this->searchColumns[] = $Columnname;
    }

    function DB_Connect ($Hostname, $Username, $Password, $Name, $Port = 3306){
        $this->DB = new mysqli(
            $Hostname,
            $Username,
            $Password,
            $Name,
            $Port
        );
    }




    function DB_Connect_Resource (mysqli &$Connection){
        $this->DB = $Connection;
    }

    function addKeyword ($Keyword){
        $this->Keywords[] = $Keyword;
    }

    function parseString ($String){
        array_map(array($this, 'addKeyword'), explode(' ', $String));
    }

    protected function query (){
        //You may want to make this query more percific to get exact results first
        //this is just a basic search for keywords
        $Q = '';
        foreach($this->searchColumns as $Column){
            foreach($this->Keywords as $Keyword){
                $Q .= sprintf("`%s` = '%s' ", $Column, $Keyword);
            }
        }
        $this->lastSearchResult = $this->DB->query(sprintf(
            "SELECT * FROM `%s` WHERE %s",
            $this->searchTable,
            $Q
        ));
    }

    function getResult (){
        if(!is_a($this->lastSearchResult, 'mysqli_result')) $this->query();
        $Result = $this->lastSearchResult->fetch_assoc();
        if($Result == NULL) return false;
        return $Result;
    }

}


//USAGE


$MyGlobalDBConnection = new mysqli('localhost', 'root', 'abcd1234', 'testdb');


$Search = new DB_Search;
$Search->DB_Connect_Resource($MyGlobalDBConnection);
$Search->setSearchTable('mytesttable');
$Search->addSearchColumn('keywords');
$Search->addSearchColumn('description');
$Search->addSearchColumn('product_name');


$Search->parseString('my test string');


while(false !== ($Result = $Search->getResult())){
    print_r($Result);
}







Read more...