php - 使用预准备语句时无法注册用户

时间:2017-09-22 01:53:14

标签: php mysqli prepared-statement

出于某种原因,我的代码在点击注册时没有注册用户。我第一次使用常规mysqli,当我将代码更改为准备好的语句时,它没有用。如果注册成功,它应该显示一条消息,即使没有将值插入数据库,它也会显示消息。

这是我的代码:

<?php
session_start();
// variable declaration
$username = "";
$email    = "";
$errors = array();
$_SESSION['success'] = "";

// connect to database
$db = mysqli_connect('localhost', 'root', 'password', 'cubetastic');

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password_1 = $_POST['password_1'];
  $password_2 = $_POST['password_2'];

  // form validation: ensure that the form is correctly filled
  // I don't think this part is relevant here

  // register user if there are no errors in the form
  if (count($errors) == 0) {
    $_SESSION['verify'] = "Your account has been created, please verify it by clicking the activation link that has been sent to your email.";
    $hash = md5(rand(0,1000)); // Generate random 32 character hash and assign it to a local variable.
    // Example output: f4552671f8909587cf485ea990207f3b
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO users (username, email, password, hash)
              VALUES(?, ?, ?, ?)";
    $stmt = mysqli_prepare($db, $query);
    mysqli_stmt_bind_param($stmt, 's, s, s, s', $username, $email, $password, $hash);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
  }
}
?>

1 个答案:

答案 0 :(得分:1)

mysqli_stmt_bind_param()上的手册清楚地显示没有使用逗号来说明要传递哪些数据类型作为参数,并与之相关,即绑定数。

我必须声明MD5不再被认为是一种安全的散列方法,尤其是在实时环境中。

分别使用password_hash()password_verify(),并确保(密码)列足够长以容纳其长度。

手册建议使用至少60长度,但声明长度为255是一个不错的选择。

参考文献:

正如我(也)在评论中所述:在查询中使用mysqli_error($db)。那会让你对这个语法错误有所了解。在开发测试期间始终使用它,并始终阅读官方手册;这就是他们的目的。