我通过createTableUsers()方法在php中创建一个表。
function createTableUsers() {
$db = Database::getInstance();
$query = "CREATE TABLE IF NOT EXISTS users (
id INTEGER AUTO_INCREMENT NOT NULL,
username VARCHAR(50) NOT NULL UNIQUE KEY,
password VARCHAR(100) NOT NULL,
email VARCHAR(50) NOT NULL,
first_name VARCHAR(50) NOT NULL default 'default_text',
last_name VARCHAR(50) NOT NULL default 'default_text'
PRIMARY KEY(id)
);";
$stmt = $db->prepare($query);
$stmt->execute();
}
当我插入新用户时:
$db = Database::getInstance();
$username = "John";
$email = "john@example.com";
$password = "john";
$this->user = new User();
$this->user->setUsername($username);
$this->user->setEmail($email);
$this->user->setPassword($password);
$this->user->save();
所以我使用User类的方法:
class User {
private $id = null;
private $username = null;
private $password = null;
private $email = null;
private $first_name = null;
private $last_name = null;
//GET & SET methods...
public static function load(array $data) {
$u = new User();
$u->id = $data['id'];
$u->setUsername($data['username']);
$u->password = $data['password'];
$u->setEmail($data['email']);
$u->setFirstName($data['first_name']);
$u->setLastName($data['last_name']);
return $u;
}
public function save() {
$new = is_null($this->id);
$db = Database::getInstance();
if($new) {
$sql = "INSERT INTO `users` (`username`, `password`, `email`, `first_name`, `last_name`) "
. "VALUES (?, ?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($this->getUsername(), $this->password, $this->getEmail(), $this->getFirstName(), $this->getLastName()));
$this->id = $db->lastInsertedId();
}
else {
$sql = "UPDATE `users` SET `username` = ?, `password` = ?, `email` = ?, `first_name` = ?, `last_name` = ? WHERE `id` = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($this->getUsername(), $this->password, $this->getEmail(), $this->getFirstName(), $this->getLastName(), $this->id));
}
}
}
但是,当我插入一个新用户时,例如在注册部分,我不知道所有字段,只知道其中的几个(用户名,密码和电子邮件)。 我想要的是一个像元组: 约翰|约翰| john@example.com | default_value | default_value。
相反,插入的元组是 John |约翰| john@example.com | NULL | NULL 即可。
我试过把'单引号',或者放'。但它是一样的,总是插入NULL。
如何输入默认值而不是NULL?我的语法错了?感谢
答案 0 :(得分:1)
如果从PHP设置它们并且使用PHP null
(将其转换为SQL的NULL
)初始化变量,则不会利用默认值。使用此:
$sql = "INSERT INTO `users` (`username`, `password`, `email`) "
. "VALUES (?, ?, ?)";
根本不要设置其他值。