PDO:使用变量来选择特定字段

时间:2014-07-02 16:15:23

标签: php pdo

我目前有以下构造来创建一个Member对象:

class Member{   
private $member_id = 0;
private $name, $surname, $email;

public function __construct(){} 

public function construct($conn, $param_select = '*', $param_member_id){
    $query_rs_this = $conn->prepare('SELECT :select FROM members WHERE 
                                            member_id = :member_id
                                        ORDER BY members.surname');

    $query_rs_this->execute(array(':select' => $param_select, ':member_id' => $param_member_id));
    $rs_this = $query_rs_this->fetch(PDO::FETCH_ASSOC);
    $query_rs_this->closeCursor();

    foreach($rs_this as $key => $value){
        $this->$key = $value;
    }
    unset($key);
}  

我想传递一个字符串,其中包含应从数据库中选择的列(字段名称)。目前我正在使用这个:

$temp = new Member();
$select = "name, surname, email";
$temp->construct($db_conn, $select, 1);

其中$ select是包含字段名称的字符串。

目前,我得到以下输出:

  

member_id:0

     

名:

     

姓:

     

电子邮件:

     

?:姓名,电子邮件

这应该是:

  

member_id:1

     

姓名:John

     姓:Doe

     

电子邮件:test@email.com

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

要完成基本相同的事情,您可以选择字段白名单,然后自己构建字段字符串。

public function construct($conn, 
                          $param_select = array('name', 'surname', 'email'),
                          $param_member_id) 
{
    $available_fields = array('name', 'surname', 'email');
    $select_fields_array = array_intersect($param_select, $available_fields);
    $select_fields = implode(", ", $select_fields_array);
    $query_rs_this = $conn->prepare("SELECT $select_fields FROM members WHERE 
                                        member_id = :member_id
                                    ORDER BY members.surname");

    $query_rs_this->execute(array(':member_id' => $param_member_id));
    $rs_this = $query_rs_this->fetch(PDO::FETCH_ASSOC);
    $query_rs_this->closeCursor();

    foreach($rs_this as $key => $value){
        $this->$key = $value;
    }
    unset($key);
}  

OR

public function construct($conn, 
                          $param_select = array('name', 'surname', 'email'),
                          $param_member_id) 
{

    $query_rs_this = $conn->prepare("SELECT * FROM members WHERE 
                                        member_id = :member_id
                                    ORDER BY members.surname");

    $query_rs_this->execute(array(':member_id' => $param_member_id));
    $rs_this = $query_rs_this->fetch(PDO::FETCH_ASSOC);
    $query_rs_this->closeCursor();

    foreach($rs_this as $item){
        foreach($param_select as $field) {
             $this->$field = $item[$field];
        }
    }
    unset($key);
}