2013-08-10 3 views
5

レコードを取得するための検索フォームがあります。そして、彼らは次のコードを検索するときSQLフィールドが文字列として出力されています

<select name="record" id="record"> 
<option value="1">Highest Score</option> 
<option value="2">Most runs</option> 
</select> 

を実行します:

if (isset($_GET['action']) and $_GET['action'] == 'search') 
{ 
    include $_SERVER['DOCUMENT_ROOT'] . '/stats/includes/db.inc.php'; 

    $placeholders = array(); 

    if($_GET['record'] == '1'){ 
     $placeholders[':record'] = 'runs'; 
    } else if($_GET['record'] == '2'){ 
     $placeholders[':record'] = 'SUM(runs)'; 
    } 

    $select = 'SELECT playerid, :record as record, user.usertitle'; 
    $from = ' FROM cricket_performance p INNER JOIN user ON p.playerid = user.userid'; 
    $where = ' WHERE TRUE'; 

    if ($_GET['team'] != '') 
    { 
    $where .= " AND team = :team"; 
    $placeholders[':team'] = $_GET['team']; 
    } 

    if ($_GET['record'] != '') 
    { 
    $where .= " ORDER BY :record DESC"; 
    } 

    $where .= " LIMIT 10"; 

    try 
    { 
    $sql = $select . $from . $where; 
    $s = $pdo->prepare($sql); 
    $s->execute($placeholders); 
    } 
    catch (PDOException $e) 
    { 
    $error = 'Error fetching record'; 
    include 'form.html.php'; 
    exit(); 
    } 

    foreach ($s as $row) 
    { 
    $records[] = array('playerid' => $row['playerid'], 'record' => $row['record'], 'usertitle' => $row['usertitle'], '1' => $row['1']); 
    } 
    include 'form.html.php'; 
    exit(); 
} 

をそして、それは除いて、完全に正常に動作しますフォームの制限フィールドの一つは、このようになりますドロップダウンボックスであること、recordです一例を挙げると。これは:runsフィールドがデータベースから選択されているのではなく、$placeholders[':record'] = 'runs';が文字通り「実行中」としてSQLに印刷されているため、$record['record']はテーブルから取り出される数値の代わりにすべてのエントリに対して '実行'として出力されます。引用は、同じことが起きる「」に置き換え、および ``に置き換えた場合、何もあなたがテーブルやフィールド名のプレースホルダを使用するべきではありません(空の結果)

答えて

1

起こるされていない場合は

。代わりに変数を使用すると、値はいずれにしてもサニタイズする必要はありません。

"SELECT playerid, ".$field." as record, user.usertitle" 
+0

完璧、ありがとう – cameronjonesweb

0

PDOは、バインドされたパラメータが、例えば、 WHERE句。したがって、

$s = $pdo->prepare($sql); 
$s->execute($placeholders); 

は期待どおりに動作しません。 PDOは

SELECT playerid, 'runs' as record, user.usertitle 

よう

SELECT playerid, :record as record, user.usertitle 

何かから作成し、実行しようとします。

関連する問題