使用 PDO 从数据库中获取单个字段的函数


Function to get single field from database with PDO

我创建了以下可重用代码,以使用动态输入从单个数据库字段中获取值:

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,即使它应该返回数据。

在 ->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;
      }
}