嘿,大家好我得到這個錯誤:捕錯誤 - 參數必須是PDO
Catchable fatal error: Argument 1 passed to Users::__construct() must be an instance of PDO, none given, called in C:\xampp\htdocs\xampp\ooplogin\register.php on line 46 and defined in C:\xampp\htdocs\xampp\ooplogin\class\Users.php on line 9
說真正的代碼工作,沒有問題,但你知道,如果我想使乾淨的代碼它shouldbt是有任何錯誤。
我的代碼:
<?php
class Users {
/* Deklarovanie premennych */
public $name = null;
public $email = null;
public $phone = null;
public $message = null;
public function __construct(PDO $db_con)
{
$this->db_con = $db_con;
}
public function storeFormValues($data)
{
if(isset($data['name'])) $this->name = stripslashes(strip_tags($data['name']));
if(isset($data['email'])) $this->email = stripslashes(strip_tags($data['email']));
if(isset($data['phone'])) $this->phone = stripslashes(strip_tags($data['phone']));
if(isset($data['message'])) $this->message = stripslashes(strip_tags($data['message']));
return $this;
}
public function message()
{
$correct = false;
try {
$sql = "INSERT INTO user(name, email, phone, message) VALUES (:name, :email, :phone, :message)";
$stmt = $this->db_con->prepare($sql);
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue("email", $this->email, PDO::PARAM_STR);
$stmt->bindValue("phone", $this->phone, PDO::PARAM_STR);
$stmt->bindValue("message", $this->message, PDO::PARAM_STR);
$stmt->execute();
return 'Sprava bola uspesne odoslana!';
}catch(PDOException $e) {
return $e->getMessage();
}
}
public function displayAll()
{
try{
$sql = "SELECT * FROM users LIMIT 10";
$stmt = $this->db_con->prepare($sql);
$stmt->execute();
return $this->$stmt;
}catch(PDOException $e) {
return $e->getMessage();
}
}
}
try {
$db_con = new PDO(DB_HOST, DB_USER, DB_PASS);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e) {
return $e->getMessage();
}
$Users = new Users($db_con);
$Users->storeFormValues($_POST);
echo $Users->message();
?>
而且我的index.php樣子:
<?php if(!(isset($_POST['send']))) { ?>
HTML FORM HERE
<?php
} else {
$Users = new Users;
$Users->storeFormValues($_POST);
if($Users->message()) {
echo "Sprava bola úspešne odoslana";
} else {
echo "Sprava nebola odoslana";
}
}
?>
這裏是一個機會,有人可以幫我解決這個問題或解釋爲什麼它不工作?謝謝!
你確定你的'$ db_con'連接正確嗎?當調用'new PDO()'時,你在'catch'中返回了$ e-> getMessage();',但是你可能沒有在任何地方看到這個錯誤。將其更改爲'echo $ e-> getMessage()'並確定它是否連接成功。常量'DB_HOST'的值是多少?這是一個有點懷疑,因爲它的名字_host_,其中PDO需要一個連接字符串,如「mysql:host = localhost; dbname = databasename」作爲其第一個參數。 –
這是我的配置。我正在包括'定義的PHP(「DB_HOST」,「mysql:host = localhost; dbname = test」); define(「DB_USER」,「root」); define(「DB_PASS」,「」); \t define(「CLASS_PATH」,「class」);' 它成功連接,因爲它添加新的數據到數據庫,只是拋出錯誤,而這樣做 –