SQL字段作为字符串打印

时间:2013-08-10 00:58:33

标签: php sql string pdo

我有一个搜索表单来获取一些记录。表单的限制字段之一是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();
}

除了一件事,这完全没问题。这样:$placeholders[':record'] = 'runs';在SQL中打印为“运行”,而不是从数据库中挑选的runs字段,因此$record['record']将被打印为每次“运行”输入,而不是从表中挑出的数字。

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

2 个答案:

答案 0 :(得分:1)

您不应对表或字段名称使用占位符。改为使用变量,无论如何都不需要对值进行消毒。

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

答案 1 :(得分: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

并尝试执行。