我有一个 php 类,用于通过 PDO 运行 SQL 语句。该类将 FetchAll 的数据存储到公共变量中的该查询但问题是我不知道查询将是什么所以我最终在数据操作查询(插入、删除、更新)上调用 FetchAll
我如何知道某个特定查询是否可获取?我不想使用诸如检查查询是否从 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));
}
}