<?php

#====================
# For more examples see: http://www.nearby.org.uk/sphinx/search-example.php

#====================

$q = isset($_GET['q'])?$_GET['q']:'';

$q preg_replace('/ OR /',' | ',$q);

$q preg_replace('/[^\w~\|\(\)\^\$\?-]+/',' ',trim(strtolower($q)));

?>
        <form action="?" method="get">
        Search: 
                <input name="q" type="text" value="<? echo htmlentities($q); ?>"/>
                <input type="submit" value="Search"/>
        </form>
<?

if (!empty($q)) {

    
//Connect to sphinx, and run the query
    
$sphinxql mysql_connect('127.0.0.1'.':'.9306,'','') or die("ERROR: unable to connect to searchd");

    
$query "SELECT id FROM myindex WHERE MATCH('".mysql_real_escape_string($q)."') LIMIT 25";
    
$result mysql_query($query,$sphinxql);        

    if ( !
$result || mysql_errno($sphinxql) > ) {
        print 
"\tQuery failed: -- please try again later.\n";
        exit;
    } else {
        
//We have a result to get details for
        
$result2 mysql_query("SHOW META",$sphinxql);
        
$res = array();
        while(
$row mysql_fetch_array($result2,MYSQL_ASSOC)) {
            
$res[$row['Variable_name']] = $row['Value'];
        }

        
$query_info "Query '".htmlentities($q)."' retrieved ".mysql_num_rows($result)." of {$res['total_found']} matches in {$res['time']} sec.\n";
    }
    
    if (
mysql_num_rows($result)) {
        
//Build a list of IDs for use in the mysql Query and looping though the results
        
$ids = array();
        while(
$row mysql_fetch_array($result,MYSQL_ASSOC)) {
            
$ids[] = $row['id'];
        }
    } else {
        
$r "\t--none--";
    }
    
    if (!empty(
$ids)) {
        
//Connect to mysql get rows
        
$db mysql_connect('localhost','username','password') or die("ERROR: unable to connect to mysql");
        
mysql_select_db('database'$db);
        
        
$sql "SELECT id, title, body FROM dbtable    WHERE id IN (".implode(',',$ids).")";
        
$result mysql_query($sql) or die ("Couldn't select query : $sql " mysql_error() . "\n");
        
$r '';
        if (
mysql_num_rows($result) > 0) {
            print 
"<ol id=\"results\">";        
            
$rows = array();
            while (
$row mysql_fetch_array($result,MYSQL_ASSOC)) {
                
$rows[$row['id']] = $row;
            }
            foreach (
$ids as $c => $id) {
                
$row $rows[$id];
                
                print 
"<li><a href=\"/page.php?page_id={$row['id']}\">".htmlentities($row['title'])."</a><br/>".htmlentities($row['body'])."</li>";
            }
            print 
"</ol><pre>$query_info</pre>";
        } else {
            print 
"--none--";
        }
    } 
    
}