我正在尝试通过带有变量的PDO创建一个插入语句,但总是会出现以下错误
Fatal error: Uncaught Error: Call to a member function prepare() on null in /Applications/XAMPP/xamppfiles/htdocs/Jobber/user.php:9 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/jobber/usercheck.php(3): Users->__construct('steve', 'testt@test.com', 'test', 1) #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/Jobber/user.php on line 9
这是我正在使用的代码
class Users{
private $connect ;
function __construct($name,$email,$password,$usertype){
include("connect.php");
$startDb = new Connect();
$this->connect = $startDb->getDb();
$sqlquery = $this->connect->prepare("INSERT INTO `user`( `Username`, `Email`, `Active`, `Password`, `usertype`) VALUES (" + $name + "," +$email +",0," + $password + "," + $usertype + ")");
$sqlquery->execute();
}
}
连接是否存在问题,或者变量是否存在其他问题?
这是连接类
class Connect{
private $host = "localhost:8080";
private $user = "root";
private $password = "test";
private $dbName = "jobber";
private $db;
function __construct(){
try{
$connection = new PDO('mysql:host=localhost;dbname=jobber',$this->user,$this->password);
}catch(PDOException $ex){
echo $ex;
}
}
function getDb(){
if($this->db instanceof PDO){
return $this->db;
}
}
}
答案 0 :(得分:1)
在Connect
课程中,您已声明private $db;
,并在$this->db
方法中返回getDb()
,但您从未为其指定过值。看起来你可能想在构造函数中这样做。
而不是
$connection = new PDO('mysql:host=localhost;dbname=jobber',$this->user,$this->password);
使用
$this->db = new PDO('mysql:host=localhost;dbname=jobber',$this->user,$this->password);
在Users
类中,使用预准备语句的更正确方法是使用占位符准备SQL语句。然后,您可以使用bindValue
手动将变量绑定到预准备语句,或者将它们传递给数组中的execute
方法,如下所示:
$sqlquery = $this->connect->prepare("INSERT INTO `user`
(`Username`, `Email`, `Active`, `Password`, `usertype`) VALUES (?, ?, 0, ?, ?)");
$sqlquery->execute([$name, $email, $password, $usertype]);
但是,说实话,在构造函数中发生这种事实对我来说似乎很奇怪。