PDO:在未知查询上使用fetchAll

时间:2013-05-23 00:46:44

标签: php pdo

我有一个用于通过PDO运行SQL语句的php类。该类在公共变量中将FetchAll的数据存储到该查询但问题是我不知道查询将是什么,所以我最终在数据操作查询(INSERT,DELETE,UPDATE)上调用FetchAll

如何知道特定查询是否可以获取?我不想使用hacks来检查查询是否从INSERT / DELETE / UPDATE开始。

class mysql {
    public $call, $rows;
    public function query($a) {
        $this->call = $pdo->prepare($a['query']);
        foreach($a['params'] as $key => $param) {$this->call->bindValue($key + 1, $param);}
        $this->rows = $this->call->fetchAll(PDO::FETCH_ASSOC);
    }
}

如果我运行操作查询,则抛出错误。

编辑:完整的课程

class mysql {
    public $call, $rows;

    // allows query on construct time
    function __construct($a = false) {if($a) $this->query($a);}
    public function query($a) {
        $this->call = $pdo->prepare($a['query']);

        // execute the query with or without parameters, and if it succeeds and dontLog is not set and the query has data manipulation then call the log function to log the query along with user id
        if($this->call->execute(isset($a['params']) ? $a['params'] : null) && !isset($a['dontLog']) && in_array(substr($a['query'], 0, 6), array('INSERT','UPDATE','DELETE'))) $this->log(isset($a['params']) ? json_encode($a['params']) : '');

        // if the call returns any columns then store it in rows public variable or store an empty array
        $this->rows = ($this->call->columnCount() > 0) ? $this->call->fetchAll(PDO::FETCH_ASSOC) : array();
    }
    private function log($params) {
        new mysql(array('query' => 'INSERT INTO logs (user, query, parameters) VALUES (?, ?, ?)', 'params' => array($GLOBALS['user']['id'], $this->call->queryString, $params), 'dontLog' => true));
    }
}

2 个答案:

答案 0 :(得分:4)

您可以尝试使用PDOStatement::columnCount

答案 1 :(得分:1)

这是一堂课!

为什么只有单一的方法,这只是一个普通的功能? 为什么要一直返回FetchAll?可以有标量返回,这将非常方便。还是单排?
为什么不为不同的结果设置单独的方法?

  • 行的取件
  • 行的fetchrow
  • 标量的fetchone
  • 查询其他所有内容

它非常方便且可读

另外,你必须改变这个奇怪的代码

foreach($a['params'] as $key => $param) {$this->call->bindValue($key + 1, $param);}

到这个

$this->call->execute($a['params']);

因为您当前的代码显然不可行。

或者,使它真的很方便

public function fetchAll($a)
{
    $params = func_get_args();
    $query = array_shift($args);
    $this->call = $pdo->prepare($query);
    $this->call->execute($params);
    return $this->call->fetchAll();
}

这样称呼:

$rows = $db->fetchAll("SELECT * FROM t WHERE cat=?",$catagory);

干净,嗯?

还有一个 - 你必须返回结果,而不是将它存储在类变量中。您的类不需要这些行,但调用代码确实如此。