PDO - 选择来自POST /参数的列

时间:2013-10-30 11:45:11

标签: php mysql pdo

是否可以使用此功能:

function getProjectData($uid, $what) {
    $sql = "SELECT ? FROM projects WHERE fid = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->execute(array($uid,$what);
    return $stmt->fetch(PDO::FETCH_LAZY);
}  

“uid”是用户ID,“what”将是我想要的列,例如“title”所以查询将是:

SELECT title FROM projects WHERE fid = 1  

这可能吗?

2 个答案:

答案 0 :(得分:1)

在PDO中无法替换表和列名称:

看看这里: Can PHP PDO Statements accept the table or column name as parameter?

答案 1 :(得分:1)

function getProjectData($uid) {
    $sql = "SELECT * FROM projects WHERE fid = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->execute(array($uid);
    return $stmt->fetch();
}

这样称呼

$proj_data = getProjectData($uid);

然后获得所需的属性

$title = $proj_data[$what];