我正在尝试使用fetchAll()
从数据库中获取数据,除非我在insert
查询后立即尝试这样做,否则它将起作用。我一直得到的错误是“一般错误”。我在网上看到这是一个知道问题:
如果你使用INSERT语句执行
$statement->query()
,然后$statement->fetch()
,你会得到一个例外:SQLSTATE [HY000]:一般错误。 source
有什么方法可以解决这个问题吗?
首先我正在运行一个插入查询:
INSERT INTO question (`qid`, `question`, `category`, `subcategory`, `explanation`, `answer_type`, `answer_options`, `answer_nav`, `answer_optional`) VALUES ('65', 'TEST', 'wisselvraag', 'wk 1 - wk 1', '<strong>Let op! Maak aantekening bij vraag.</strong>', 'yes_no', '{null,null}', '', '1')
private function get($columns = "*", $dump = false)
{
$this->select($columns);
$this->prepareSQL();
if ($dump === true) {
$this->dumpSQL();
return [];
}
$this->stmt = $this->getPdo()->prepare($this->query);
$this->stmt->execute();
$this->incrementAmountOfQueries();
return $this->stmt->fetchAll(\PDO::FETCH_ASSOC);
}
在执行此操作后,我运行SELECT
查询:
SELECT question.* FROM question JOIN questionlist_question ON questionlist_question.`question_id` = question.`id` WHERE question.`category` = 'wisselvraag' AND questionlist_question.`questionlist_id` = '7' ORDER BY question.`qid` DESC LIMIT 1
要
$this->stmt->execute();
$this->stmt->fetchAll(\PDO::FETCH_ASSOC);
我的数据。 fetchAll()
似乎是个问题。
/**
* prepare an INSERT query
* @param array $data
* @return bool
*/
private function insert(Array $data)
{
$fields = "";
$values = "";
foreach ($data as $field => $value) {
$value = htmlentities($value);
$fields .= "`$field`, ";
$values .= "'$value', ";
}
$fields = trim($fields, ", ");
$values = trim($values, ", ");
$this->insert = "($fields) VALUES ($values)";
$this->incrementAmountOfQueries();
return $this->execute();
}
/**
* Execute a query
* @return bool
*/
private function execute()
{
$this->prepareSQL();
// print($this->query);
// exit;
$this->stmt = $this->getPdo()->prepare($this->query);
return $this->stmt->execute();
}
$这 - &GT;语句
$this->stmt
定义为$this->stmt = $this->getPdo()->prepare($this->query);
getPdo()
/**
* Get PDO instance
* @return \PDO
*/
private function getPdo()
{
if (!$this->pdo) {
try {
$this->pdo = new \PDO($this->dsn, $this->username, $this->password);
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
} catch (\Exception $err) {
print_r($err);
exit;
}
}
return $this->pdo;
}
$这 - &GT;查询
private function prepareSQL()
{
$sql = "";
if ($this->insert) {
if ($this->table) {
$sql .= "INSERT INTO " . $this->table;
$sql .= " " . $this->insert;
}
} else {
if ($this->select) $sql .= "SELECT " . $this->select;
if ($this->table) $sql .= " FROM " . $this->table;
if ($this->join) $sql .= " " . $this->join;
if ($this->where) $sql .= " " . $this->where;
if ($this->order) $sql .= " " . $this->order;
if ($this->limit) $sql .= " LIMIT " . $this->limit;
}
$this->query = $sql;
return $this;
}
答案 0 :(得分:0)
是。
我想你是从函数中返回这个值的。那么,请返回一份声明。然后,如果需要获取行,请稍后将fetchAll()链接到函数调用。 您不会相信您的功能会变得多么灵活。
您可以查看此类功能的示例部分:all this stuff仅在返回的语句中可用。
您可能还想阅读我的其他文章Your first database wrapper's childhood diseases,因为我确定您的包装器还有其他问题。