为了简单起见,我们假设我们有这个相当人为的表格:
[ID] [Weekday] [Weather]
1 Sun Cloudy
2 Mon Sunny
... ... ...
8 Sun Cloudy
... ... ...
15 Sun Windy
我正在为数据集敲击该表。有时我想要基于工作日的数据,有时候基于天气。所以我创建了这个类:
class weather {
public static function reportByDay($weekday) {
return self::weatherServer('Weekday',$weekday);
}
public static function reportByWeather($weather) {
return self::weatherServer('Weather', $weather)
}
private static function weatherServer($reportType, $value) {
$q = "SELECT ID, Weekday, Weather
FROM table
WHERE $reportType = $value";
$r = mysql_query($q);
etc etc.
return $results;
}
}
所以我想把它转换为PDO,但今天早上发现WHERE :field = :thing
结构不起作用......至少我不能使它工作。
如果我描述了列,那么WHERE Weather = :thing
那么它运行得很好......但是我刚刚失去了原始类结构的便利性,因为我必须输入所有这些专门的查询。我的真实数据集&有很多。表结构。
是否有PDO方法将列用于列?或者params只能用于值?
答案 0 :(得分:3)
保留一个安全列表并使用字符串连接或插值将列名放在那里。
$validColumns = array(
'Weather',
'Weekday'
);
if ( ! in_array($reportType, $validColumns)) {
throw new Exception('Not a valid column name.');
}
$q = "SELECT ID, Weekday, Weather
FROM table
WHERE `$reportType` = :value";
答案 1 :(得分:3)
看起来你已经有了一半的答案 - 不要让PDO绑定列,像你一样“手动”执行:
private static function weatherServer($reportType, $value) {
// you may want to sanitize reportType, but because this is private, you
// might not need to
$q = "SELECT ID, Weekday, Weather
FROM table
WHERE $reportType = :value";
// no idea where $pdo would be declared in your framework. It's up to
// what you feel best meets your need.
$stmt = $pdo->prepare($q);
$stmt->bindParam(":value",$value);
etc etc.
return $results;
}