我有一个搜索表格来获取一些记录。表单的限制字段之一是record
,它是一个下拉框,如下所示:
<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();
}
这工作得很好,除了一件事。This:$placeholders[':record'] = 'runs';
在 SQL 中确实被打印为“runs”,而不是runs
从数据库中选择字段,因此$record['record']
每个条目都将打印为“runs”,而不是从表中挑选出的数字。
如果引号被替换为“”,同样的事情发生,如果被替换为``没有任何反应(空结果)