我创建了以下可重用代码,以使用动态输入从单个数据库字段中获取值:
function query_column($columnName,$tableName,$whereColumn,$whereValue) {
global $db;
$query = $db->prepare("SELECT :columnName FROM " . htmlspecialchars($tableName) . " WHERE :whereColumn = :whereValue LIMIT 1");
$query->execute(array(':columnName' => $columnName, ':whereColumn' => $whereColumn, ':whereValue' => $whereValue));
if($query->rowCount() > 0) {
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
return $result['$columName'];
}
} else {
return Null;
}
}
我称之为:
$this->author = query_column("name","author","authorid",$authorId);
我已经发现你不能将表名与PDO的参数绑定,但我还能做些什么呢?它仍然返回Null,即使它应该返回数据。
答案 0 :(得分:1)
在 - > prepare()语句
之外准备字符串function query_column($columnName,$tableName,$whereColumn,$whereValue) {
global $db;
$sql = "SELECT $columnName FROM " . htmlspecialchars($tableName) . " WHERE $whereColumn = :whereValue LIMIT 1";
$query = $db->prepare($sql);
$query->execute(array(':whereValue' => $whereValue));
if($query->rowCount() > 0) {
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
return $result['$columName'];
}
} else {
return Null;
}
}