閱讀原文:http://yzswyl.cn/blread-1611.html
1.未採用mysql二進位網路通訊協定的代碼:
//檢查sphinx是否能串連,不能重試兩次,能則串連,不用mysql協議,僅供參考function checkSphinxNoMysql() { $flag = true; $retries = 0; while ( $flag && $retries < 2 ) { $s = new SphinxClient (); $s->setServer ( $_ENV ['db_host'], $_ENV ['current_sphinx_port'] ); if (! $s->open ()) { //此處為如果串連不上就更改設定檔,根據項目需要來寫 //global $configDefault; //updateConfig ( $configDefault ); $retries ++; } else { $flag = false; break; } } return $s; if ($retries >= 2) { //sendemail or not return false; }} $order_column = 'id DESC,time DESC';//定序//$s = checkSphinx ();$s = new SphinxClient ();$s->setServer ( 'sphinx_host', 'sphinx_port');//以上兩句代碼亦可使用$s = checkSphinx ();來代替$indexname = "page_keyword";//索引名字$s->setMatchMode ( SPH_MATCH_PHRASE );$s->SetSortMode ( SPH_SORT_EXTENDED, $order_column );$s->setMaxQueryTime ( 100000 );$s->setLimits ( 0, $limit_total, $limit_total );$keyword_sphinx = iconv ( "gbk", "utf-8", $keyword );$result = $s->query ( $keyword_sphinx, $indexname );$s->close ();if ($result ['total'] > 0) { var_dump($result ['matches']); //根據列印出的結果進行相應的讀取}
2.採用mysql二進位網路通訊協定的代碼:
//檢查sphinx是否能串連,不能重試兩次,能則串連,用mysql14協議protected function checkSphinx() { $flag = true; $retries = 0; while ( $flag && $retries < 2 ) { $conn = mysql_connect ( "{$_ENV ['db_host']}:{$_ENV ['current_sphinx_port']}" ); if (! $conn) { //此處為如果串連不上就更改設定檔,根據項目需要來寫 //global $configDefault; //updateConfig ( $configDefault ); $retries ++; } else { $flag = false; break; } } if ($retries >= 2) { die ( "Please contact with administrator." ); } return $conn;} $order_column = 'id DESC,time DESC';//定序$conn = mysql_connect ( "sphinx_host:sphinx_port" );//以上代碼亦可使用$conn = checkSphinx ();來代替if (! $conn) { return - 1;//串連不上返回狀態}$keyword_sphinx = iconv ( "gbk", "utf-8", $keyword );//keyword為索引名字$sql = "select * from keyword where match('{$keyword_sphinx}') order by {$order_column} limit {$limit_total} option max_matches={$limit_total}";$result = @mysql_query ( $sql, $conn ); $i = 0;while ( ($row = mysql_fetch_array ( $result )) !== false ) { var_dump($row); //根據列印出的結果進行相應的讀取}$totals = $this->getTotalFound ($conn);//擷取總記錄個數
如何擷取總記錄個數參考:sphinxql如何得到結果數?show meta的詳細說明?
關於開啟mysql二進位網路通訊協定參考:Sphinx/MySQL 協議支援與SphinxQL