我正在用PHP和SQLite创建一个登录系统,在将用户插入数据库的逻辑中,我的代码如下:
<?php
class my_db extends SQLite3 {
public $first_name;
public $last_name;
public $email;
public $password;
public function __construct($first_name, $last_name, $email, $password) {
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->email = $email;
$this->password = $password;
$this->open("didactic-eureka.db");
}
public function create_user_table() {
$sql = <<<EOF
CREATE TABLE IF NOT EXISTS USER(
ID PRIMARY KEY NOT NULL ,
FIRST_NAME TEXT NOT NULL ,
LAST_NAME TEXT NOT NULL ,
EMAIL TEXT NOT NULL ,
PASSWORD TEXT NOT NULL
);
EOF;
$this->exec($sql);
}
public function insert_user() {
$sql = <<<EOF
INSERT INTO USER(FIRST_NAME, LAST_NAME, EMAIL, PASSWORD)
VALUES ($this->first_name,$this->last_name,$this->email,$this->password);
EOF;
46 $insert = $this->exec($sql);
if (!$insert) {
$this->lastErrorMsg();
} else {
echo "User Inserted into the database";
}
}
}
if (isset($_POST["submit"])) {
// Get value from form
$first_name = htmlspecialchars($_POST['first_name']);
$last_name = htmlspecialchars($_POST['last_name']);
$email = htmlspecialchars($_POST['user_email']);
$password = htmlspecialchars($_POST['user_password']);
// Check if values is empty
if (empty($first_name) || empty($last_name)) {
$err = "alert alert-danger";
$err_msg = "Please enter a first or last name";
} else {
if (empty($email)) {
$err = "alert alert-danger";
$err_msg = "An email is required";
} else {
if (empty($password)) {
$err = "alert alert-danger";
$err_msg = "A password is required";
} else {
// Hash password when all parameters are passed
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$db = new my_db($first_name, $last_name, $email, $hashed_password);
// Create table
$db->create_user_table();
// Insert data into table
$db->insert_user();
}
}
}
}
?>
当我在浏览器中进行尝试时,它会返回以下响应:
警告:SQLite3 :: exec():“ @ gmail”附近:第46行上的/var/www/html/index.php中的语法错误
我该如何解决?
答案 0 :(得分:0)
我终于找到了解决问题的办法。在我将从表单中获取的值插入数据库时,每个值都必须用单引号引起来,如下所示:
$sql = <<<EOF
INSERT INTO USER(FIRST_NAME, LAST_NAME, EMAIL, PASSWORD)
VALUES ('$this->first_name','$this->last_name','$this->email','$this->password');
EOF;