我正在进入MySQLi,我正在慢慢掌握一切。我有一段代码可用于将表单值插入到数据库中。
我不希望它只是工作,我真的想做最好的练习。我相信我已经涵盖了所有内容,但我会欣赏额外的眼睛,以帮助看看我可能错过的东西,或者更好的方法来构建代码。
// Check the form is posted
if (isset($_POST["name"])) {
// Let's get things started
$stmt = $db->prepare("INSERT INTO users (name, email, password, active, username, masteradmin, properties) VALUES (?, ?, ?, ?, ?, ?, ?)");
// Form variables
$name = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$active = mysqli_real_escape_string($db, $_POST['active']);
$username = mysqli_real_escape_string($db, $_POST['username']);
$masteradmin = mysqli_real_escape_string($db, $_POST['masteradmin']);
$properties = mysqli_real_escape_string($db, $_POST['properties']);
// Bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$stmt->bind_param('sssssss', $name, $email, $password, $active, $username, $masteradmin, $properties);
// Execute and Go!
$stmt->execute();
// Get the ID of what has been inserted
$helloid = $db->insert_id;
// Wrap things up
$stmt->close();
// Send it on its merry way.
$insertGoTo = "index.php";
header(sprintf("Location: %s", $insertGoTo));
}
答案 0 :(得分:2)
两条快速反馈
您不需要同时使用mysqli_real_escape_string
和准备好的陈述。后者足够(并且优越)。
永远不要存储明文密码!!存储前始终使用哈希和盐。
要存储,首先要执行:
$hashed_pwd = password_hash($_POST['password'],PASSWORD_DEFAULT);
//now you can store $hashed_pwd in DB
登录时,验证用户提交的密码:
//first select user from DB with matching username
//then verify the cleartext pwd submitted
if(password_verify($cleartext_pwd, $hashed_pwd)){
//correct password
}else {/*wrong password*/}
答案 1 :(得分:0)
将值插入 MySQL 数据库的最佳做法是使用 PDO 。
// Define the data array to insert
$insert = $_POST;
// remove the extra fields
unset($POST['submit']);
// create a hash
$insert['password'] = password_hash($insert['password'],PASSWORD_DEFAULT);
// Define a query.
$sql = "INSERT INTO users (name, email, password, active, username, masteradmin, properties)
VALUES (:name, :email, :password, :active, :username, :masteradmin, :properties)";
// Prepare, execute and Go!
$stmt = $db->prepare($sql)->execute($insert);