gpt4 book ai didi

php - PDO:在未知查询上使用 fetchAll

转载 作者:行者123 更新时间:2023-12-02 11:59:50 25 4
gpt4 key购买 nike

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

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));
}
}

最佳答案

您可以尝试使用PDOStatement::columnCount

关于php - PDO:在未知查询上使用 fetchAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com