// connection.php file
<?php
class Connection{
private $host;
private $username;
private $password;
private $database;
public function __construct($host,$username,$password,$database)
{
try{
$conn = new PDO("mysql:host=".$host.";dbname=".$database, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch(PDOException $e)
{
return $e->getMessage();
}
}
}
?>
// user.php
<?php
class Users extends Connection{
private $username;
private $email;
private $password;
public function __construct($username,$email,$password){
$this->username=$username;
$this->email=$email;
$this->password=$password;
}
public function addUser(){
$conn = new Connection("localhost","root","","userdata");
echo "database connection established";
die();
$sql = $conn->prepare("INSERT INTO information (UserName, Email, Password) VALUES (?, ?, ?)");
$conn->bind_param("sss", $username, $email, $password);
$username=this->username;
$password=this->password;
$email=this->email;
$sql->execute();
echo "New records created successfully";
$sql->close();
$conn->close();
}
}
?>
process.php
<?php
include('lib/connection.php');
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']))
{
$user = new User("Gautam","gautam@mail.com","123456");
$user->addUser();
}
?>
所以问题,当我尝试执行process.php文件时,记录没有添加到数据库中。所以我已经分别创建了连接类,我已经编写了数据库连接的逻辑,然后我继承了该类给用户我将用户添加到数据库然后我在process.php中调用了用户类的对象,但是没有将记录添加到数据库中。请说明与之相关的问题。
答案 0 :(得分:0)
您的代码存在的问题是您在执行之前没有绑定任何参数。
检查这些行:
$sql = $conn->prepare()
$conn->bind_param("sss", $username, $email, $password);
此行应为$sql->bind_param("sss", $username, $email, $password);
并注意到PDO没有bind_param()
函数:bindParam()
因此你需要
$sql->bindParam(1, $this->username);
$sql->bindParam(2, $this->email);
$sql->bindParam(3, $this->password);
以下代码应该有效:
<?php
class Users extends Connection
{
private $username;
private $email;
private $password;
public function __construct($username, $email, $password)
{
$this->username = $username;
$this->email = $email;
$this->password = $password;
}
public function addUser()
{
$conn = new Connection("localhost", "root", "", "userdata");
echo "database connection established";
$username = $this->username;
$password = $this->password;
$email = $this->email;
$sql = $conn->prepare("INSERT INTO information (UserName, Email, Password) VALUES (?, ?, ?)")->execute(array($username,$email,$password));
if (!$sql) {
print_r("error : " . $conn->errorInfo());
} else {
echo "New records created successfully";
}
$sql->close();
$conn->close();
}
}
?>
PS:不要以纯文本形式存储密码,使用php内置函数等 用password_hash()
和password_verify()
来准备密码。
答案 1 :(得分:-1)
首先在你的班级中使用$ this代替这个,然后你拨打错误的班级名称User,这是用户,请修改并尝试,应该工作。
$user = new Users("Gautam","gautam@mail.com","123456");
在用户类
的adduser函数中$username=$this->username;
$password=$this->password;
$email=$this->email;
如上所述改变它应该有效..