[英]Need help to find error SQLSTATE[HY000]: General error
我正在向數據庫中插入一行。 它工作正常,但是當我啟用PDO錯誤消息時,它給了我這個錯誤。 我想確切知道為什么會出現此錯誤,以便在開發過程中保持啟用錯誤消息的功能。 這是我的代碼:
啟用我放入數據庫類的錯誤
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
我班上的數據庫連接
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), config::get('mysql/username'), config::get('mysql/password'));
$this->_prefix = '';
} catch (PDOException $e) {
die($e->getMessage());
}
這是我調用查詢的方法
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x=1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error= true;
}
}
return $this;
}
這是我的數據庫類中的插入函數
public function insert($table, $fields = array()){
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach ($fields as $field) {
$values .= "?";
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
if (!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
這是我的游覽類中的函數,該函數通過調用insert函數將所有數據保存到DB。
public function create($fields= array()){
if(!$this->_db->insert("tours", $fields)){
throw new Exception('There was a problem creating Tours.' .print_r($this->_db->error()));
}
}
保持啟用ATTR_ERRMODE的原因是因為它可以幫助我在開發過程中進行調試,並且仍有許多頁面需要開發。 我已經訪問過許多類似的問題,但它們與錯誤有關。 我通常不會收到任何錯誤,只有在啟用此錯誤消息傳遞系統后才能得到,該錯誤消息系統會告訴我所有詳細信息。
這不同於其他問題,因為它沒有給我錯誤,但它成功插入行,但是當我啟用錯誤模式時,它給了我錯誤。 另一個我正在使用動態參數,因此無法添加冒號:來糾正它。 與查詢數據庫的功能相同。
我對Aynber表示歉意,因為他是對的,我無法理解答案,因此必須從函數中刪除fetchAll。 因此,我現在創建了兩個函數,一個用於插入/更新,另一個用於查詢。 答案在那里,但我看到了其他答案。
我剛剛從查詢功能中刪除了以下行
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
現在,我的課程很好,因為它正在執行正確的錯誤處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.