我无意中发现了这种行为,现在我很好奇到底发生了什么。如果我试图将参数绑定到GROUP BY子句中的列名,数据实际上将被返回,但只返回一行。我知道您是https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter,使用表名或列名作为参数,但我想知道是什么原因导致这种情况在幕后发生。这深深地隐藏在我的(业余)代码中,而且很难排除故障,因为它没有抛出一个错误,它实际上返回了数据。我希望有更多的洞察力!
样本表:
| artist | album | label |
|-----------------|----------------|-------------|
| John Coltrane | A Love Supreme | MCA Records |
| John McLaughlin | Extrapolation | Marmalade |
| John Coltrane | A Love Supreme | Impulse! |
| John McLaughlin | Extrapolation | Polydor |示例代码:
$field = 'artist';
$artist = '%john%';
$sql = 'SELECT artist, album
FROM record_collection
WHERE artist LIKE :artist
GROUP BY :field';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':artist', $artist);
$stmt->bindParam(':field', $field);
$stmt->execute();
echo 'Row count: '. $stmt->rowCount();返回:“行数: 1”
我注意到:
所以我想知道的是:
发布于 2016-08-14 15:41:59
当您传入:field时,您将传入一个字符串值。因此,结果是group by <constant>,它返回一行。
不能参数化列名,因此必须将其直接放入SQL语句中:
$sql = 'SELECT artist, album
FROM record_collection
WHERE artist LIKE :artist
GROUP BY '.$field':artist很好,因为它是一个值,而不是SQL中的标识符。
https://stackoverflow.com/questions/38943718
复制相似问题