在获取数据PDO PHP时,是否可以将字段名作为$variable传递


Is it possible to pass field name as $variable while fetching data PDO PHP?

这是我的代码:-_US是主表中一个字段的名称。它包含数值

$count = '_US'; $random_id = '1';
$stmt = $db->prepare("SELECT id, name, :count FROM main_table WHERE id=:got_id LIMIT 1");
        $stmt->bindValue(':count',$count,PDO::PARAM_STR);
        $stmt->bindValue(':got_id',$random_id,PDO::PARAM_STR);
        try{
            $stmt->execute();  $count = $stmt->rowCount();
            if($count > 0){
                while($row = $stmt->fetch(PDO::FETCH_OBJ)){
                echo "ID - ".$row->id." , Name - ".$row->name." & Its Value -".$row->$count."<br/>";
                }
            }
            else{ echo "Error Occured<br/>";}
        }
        catch(PDOException $xyz ){
        // some code
        }

结果是:ID-1,名称-美国&其值-US

问题:它没有生成数值。它只是返回字段名-US

超短答案。编号

长话短说:不,他们不能。

表名和列名不能作为参数传递。当然,您可以手动清理数据并使用变量。

switch($input)
{
    case 'user':
        $columnName='user';
        break;
    default:
        $columnName='id';
        break;
}
$sql="select ".$columnName." from someTable";

但是,您可以将value传递到查询中,并将其作为查询的一部分返回:

$var="SomeString";
$sql="select id, '".$var."' as someField from someTable where id=:id";