嘿,大家好我得到这个错误:捕错误 - 参数必须是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”);' 它成功连接,因为它添加新的数据到数据库,只是抛出错误,而这样做 –