2009-09-15 20 views
1

私はシンプルな検索ページを作成しようとしていますが、私は(変数が存在する場合など、適切かつ者を使用して)実際の検索文字列を作成する方法を100%わからないんだけど、ここのコードです:mysql検索文字列を動的に作成しますか?

if ($post) { 

    //get all search variables 
    $type = JRequest::getVar('type'); 
    $classifications = JRequest::getVar('classifications', array(0), 'post', 'array'); 
    $rating = JRequest::getVar('rating'); 
    $status = JRequest::getVar('status'); 
    $cterms = JRequest::getVar('cterms'); 
    $clientid = JRequest::getVar('clientid'); 
    $company = JRequest::getVar('company'); 
    $address = JRequest::getVar('address'); 
    $name = JRequest::getVar('name'); 
    $surname = JRequest::getVar('surname'); 
    $city = JRequest::getVar('city'); 
    $state = JRequest::getVar('state'); 
    $pcode = JRequest::getVar('pcode'); 
    $country = JRequest::getVar('country'); 

    //create search string 
    echo "SELECT * FROM #__db_clients "; <- the query is supposed to be done here.. it's in as echo because I was trying to spit it out before trying to make it run.. :) 

} else { 

    echo 'There has been an error, please try again.'; 

}; 

私は(タイプ!= nullの場合は、検索タイプ= "どこでタイプ= 'X' ')を使用しようとしましたが、それは検索のために必要な場合は前と後の配置方法を理解できませんでした..センス?

答えて

2

これは簡単な例です。私はJRequest :: getVarがどのような種類のデータを返すかはわかりませんが(いつも文字列か型が混ざっていますか?)、これはあなたから始めるべきです。 foreachループ内で適用されるエスケープ方法を必ず使用してください:

if ($post) { 
    $criteria = array(); 
    //get all search variables 
    $criteria['type'] = JRequest::getVar('type'); 
    $criteria['classifications'] = JRequest::getVar('classifications', array(0), 'post', 'array'); 
    $criteria['rating'] = JRequest::getVar('rating'); 

    //if there are some criteria, make an array of fieldName=>Value maps 
    if(!empty($criteria)) { 
     $where = array(); 
     foreach($criteria as $k => $v) { 
      //IMPORTANT!! 
      //$v is the value of the field, needs to be quoted correctly!! 
      $where[] = "$k = '$v'"; 
     } 
    } 
    //create search string 
    $query = "SELECT * FROM #__db_clients"; 

    if($where) { 
     $query .= " where " . join(' AND ', $where); 
    } 
} else {  
    echo 'There has been an error, please try again.'; 
}; 
+2

エスケープを式に挿入する際には、必ず「$ v」にエスケープしてください。 –

+1

@Bill Karwin - ありがとう、絶対に!彼のアプリケーションにどのエスケープ方法が当てはまるのかわからないので、私は答え(コードコメントと同様に)にメモを入れます。 – karim79

+0

ありがとうございます、それは私のコードを手に入れるのを助けてくれるでしょう:)とても高く評価しました! – SoulieBaby

関連する問題