1

我编写了一个函数,它从我的数据库中选择所有用户以及使用 PDO 的所有对应字段。我还允许该函数将数组作为参数以方便过滤。我的问题是当我将过滤器数组传递给执行函数时,我没有从表中获得任何行。我知道它与 PDO 以及我将数组传递给它的方式有关,因为当我运行带有硬编码到查询中的过滤器的执行方法时,它可以工作。这是我的函数和调用它的代码:

$config = array(
    'filters' => array(
        'all members'     => array('',  ''),
        'officers'            => array('statuses.position_id', '8'),
        'current members'     => array('users.alumni', 0)
    )
);

$filter = $config['filters'];
//Requested filter is just a constant used to keep track of the parsed $_GET value
$result = $dbh->getUsers($filter[REQUESTED_FILTER]);

//Just showed function, not whole class
public function getUsers(array $filter = array('', '')) {
  $result = array();

  $sql = 'SELECT users.firstname, users.lastname, users.grad_year, users.alumni, users.signedISA, phone_numbers.phone_number, emails.email_address,
                addresses.name, addresses.street, addresses.city, addresses.state, addresses.zip
           FROM 
              ((users LEFT JOIN phone_numbers 
                 ON users.user_id = phone_numbers.user_id) 
                 LEFT JOIN emails 
                 ON users.user_id = emails.user_id)
                 LEFT JOIN addresses
                 ON users.user_id = addresses.user_id
                 WHERE ? = ?;';

  $sth = $this->handle->prepare($sql);

  if($sth->execute($filter)) {
     while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        array_push($result, $row);
     }
  }

  return $result;
}

任何人都知道为什么这不起作用?

4

1 回答 1

1

您不能将架构对象标识符(如表或列名)作为参数传递给准备好的语句(您当前的尝试始终是比较WHERE子句中的参数化字符串文字)。

相反,您需要执行以下操作:

public function getUsers(array $filter = array('\'\'', '')) {
  $result = array();

  $sql = 'SELECT users.firstname, users.lastname, users.grad_year, users.alumni, users.signedISA, phone_numbers.phone_number, emails.email_address,
                addresses.name, addresses.street, addresses.city, addresses.state, addresses.zip
           FROM 
              ((users LEFT JOIN phone_numbers 
                 ON users.user_id = phone_numbers.user_id) 
                 LEFT JOIN emails 
                 ON users.user_id = emails.user_id)
                 LEFT JOIN addresses
                 ON users.user_id = addresses.user_id
                 WHERE ' . $filter[0] . ' = ?;';

  $sth = $this->handle->prepare($sql);

  if($sth->execute($filter[1])) {
     while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        array_push($result, $row);
     }
  }

  return $result;
}

如果 的值超出您的控制范围,请注意 SQL 注入$filter(您需要用反引号引用标识符并将其中包含的任何反引号加倍:确保以多字节安全的方式执行此操作!)。

于 2012-09-15T01:48:06.747 回答