5

我有一个搜索表格来获取一些记录。表单的限制字段之一是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”,而不是从表中挑选出的数字。

如果引号被替换为“”,同样的事情发生,如果被替换为``没有任何反应(空结果)

4

2 回答 2

1

您不应该使用占位符来表示表名或字段名。请改用变量,无论如何都不需要对值进行清理。

"SELECT playerid, ".$field." as record, user.usertitle"
于 2013-08-10T01:11:15.150 回答
0

PDO 期望绑定参数是例如 WHERE 子句中的值。所以

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

不会按预期工作。PDO 创建自

SELECT playerid, :record as record, user.usertitle

就像是

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

并尝试执行。

于 2013-08-10T01:19:11.180 回答