在嘗試從數據庫中獲取數據時發生錯誤,該數據基於從前一頁上的i按鈕獲取的id。當我呼應ID只有它給了我正確的ID,但在完整的查詢它給我這個錯誤:帶有消息'SQLSTATE [HY093]的未捕獲異常'PDOException':在從數據庫中獲取信息時
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in
我發現了一些關於這個SO答案,但沒有人解決了這個問題,我有。
<?php
$fetch_article_info = $db->query("select * from news_article where id = :id");
$fetch_article_info->execute(array(':id' => $_GET['id']));
$list = $fetch_article_info->fetchAll(PDO::FETCH_ASSOC);
?>
下面是一些在db.class我的公開funtions,我認爲可能是有用的
class Database{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
// database handler
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
將'query'變成'prepare'調用,你用佔位符準備一個語句,然後用參數執行它。 '$ fetch_article_info = $ db-> prepare(「select * from news_article where id =:id」);' – Fracsi
@Fracsi感謝您的回覆,在獲得警告之前嘗試過:PDO :: prepare():SQLSTATE [00000]:否錯誤:當我使用準備時未調用PDO構造函數 – marijn
您的錯誤指出問題,您的參數綁定不正確。 – Option