我创建了一个类,我一直在破坏我的大脑,试图找出如何从用户获取表单信息并使用oop prepared语句将其存储在数据库中。我将展示代码。请有人告诉我,我做错了什么。
我班级的代码
<?php include '../includes/Constants.php'; ?>
<?php
class User {
public $id,
$fname,
$lname,
$email,
$username,
$password,
$conf_pass;
protected $db_conn;
//declare variables
public function __construct() {
$host = DB_HOST;
$user = DB_USER;
$pass = DB_PASS;
$db = DB_NAME;
//Connect to database
$this->db_conn = new mysqli($host, $user,$pass, $db);
//Check database connection
if ($this->db_conn->connect_error) {
echo 'Connection Fail: ' . mysqli_connect_error();
exit();
} else {
echo 'Connected';
}
}
function regUser($fname, $lname, $email, $username, $password, $conf_pass) {
if ($this->db_conn->prepare("INSERT INTO USERS (`user_id`,`user_fname`,`user_lname`,
`user_email`,`username`,`user_pass`) VALUES (NULL,?,?,?,?,?)")) {
//Bind-para to values from form
$stmt->bind_param('isssss', $id, $fname, $lname, $email, $username, $password);
//execute statement
$stmt->execute();
$this->id = $id;
$this->fname = $fname;
$this->lname = $lname;
$this->email = $email;
$this->username = $username;
$this->password = $password;
//end statement
$stmt->close();
}
}
}
?>
以下是我用来创建对象的代码。
<?php include_once 'User.php'; ?>
<?php
//Creating new User Object
$newUser = new User();
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$conf_pass = $_POST['conf_pass'];
$newUser->regUser($fname, $lname, $email,$username, $password, $conf_pass);
?>
以下是我的测试表格的代码。请告诉我我做错了什么。非常感谢任何帮助。
<html>
<head>
<title></title>
<link href="stylesheets/styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form action = "Resources/testClass.php" method="post" enctype="multipart/form-data">
<label>First Name: </label>
<input type="text" name="fname" id="fname" size="25" maxlength="25"/>
<label>Last Name: </label>
<input type="text" name="lname" id="lname" size="25" maxlength="25"/>
<label>Email: </label>
<input type="text" name="email" id="email" size="25" maxlength="40"/>
<label>Username: </label>
<input type="text" name="username" id="username" size="25" maxlength="32"/>
<label>Password: </label>
<input type="password" name="password" id="password" size="25" maxlength="32"/>
<label>Re-enter Password: </label>
<input type="password" name="conf_pass" id="conf_pass" size="25" maxlength="32"/>
<br /><br />
<input type="submit" name="submit" id="submit" value="Register"/>
<input type="reset" name="reset" id="reset" value="Reset"/>
</form>
</body>
</html>
答案 0 :(得分:0)
我猜user_id是主键,是自动增量。你不需要为user_id插入值,也可以从绑定参数中删除它。
if ($this->db_conn->prepare("INSERT INTO USERS (`user_fname`,`user_lname`,
`user_email`,`username`,`user_pass`) VALUES (?,?,?,?,?)"))
并将bind_param更改为
$stmt->bind_param('sssss', $fname, $lname, $email, $username, $password);