I created the following reusable code to get the value from a single database field using dynamic input:
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;
}
}
I call it like this:
$this->author = query_column("name","author","authorid",$authorId);
I already figured out that you can't bind the table name to a parameter with PDO, but what else could I be doing wrong? It keeps returning Null even though it should be returning data.