【问题标题】:Do i need to use $stmt = $conn->prepare for this prepared statement?我需要为这个准备好的语句使用 $stmt = $conn->prepare 吗?
【发布时间】:2019-07-03 14:34:39
【问题描述】:

我准备好的语句的当前语法不正确,其中我:(INSERT...?, ?, ?)

我尝试从不同的示例中复制语法,但似乎我尝试的次数越多,我的登录系统就越崩溃。 我有一些相互矛盾的例子,不确定哪种语法是正确的。我需要在 INSERT 之前使用 $stmt = $conn->prepare 吗?

// create preprepared statement
$sql = "INSERT INTO `user` (username, password, email) VALUES (?, ?, ?)";

// check if sql statement is correct
if ($stmt = mysqli_prepare($connection, $sql)) {

    // Add the variables to the stmt
    mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_hashed_password, $param_email);
    $param_username = $username;
    $param_password = $hashed_password;
    $param_email = $email;

    // Attempt to execute the stmt
    if(mysqli_stmt_execute($stmt)) {
        // If statement executed
        $_SESSION["username"] = $username;
        header("location: login.php");

目前它没有向我的数据库中插入任何值,并且用户注册失败。

编辑:

$password = $_POST['password'];

$hashed_pa​​ssword = password_hash($password, PASSWORD_DEFAULT);

我突然想到这可能是密码哈希的错误使用?

【问题讨论】:

  • $param_hashed_passwor != $param_password
  • 你在你的绑定语句之后定义了你的参数。
  • @user9189147 - 在mysqli这样做很好
  • 啊,感谢您指出这一点,但修复错字后仍然出现相同的错误。
  • @JoeS。你得到什么错误?

标签: php mysqli prepared-statement


【解决方案1】:

Do i need to use "$stmt = $conn->prepare" for this prepared statement? - 简而言之,不!但是,您必须使用prepare 方法来实际生成prepared statement,它必须在实际尝试执行INSERT 之前完成,并且将其分配给一个变量是明智的,这样您就可以分叉依赖于的程序逻辑成功/失败。

我的偏好是如下执行 - 使用 try/catch 块并在各个阶段使用返回值或变量来确定是否抛出有意义的(?)异常以帮助调试 - 例如您可以这样做

/*
    assumed that $username,$password & $email 
    are all defined and available at ths stage.

    also assumed that `session_start()` has 
    been called and that no html output occurs
    before this point ( unless using output buffering )
*/

try{
    # example

    $sql = "INSERT INTO `user` ( `username`, `password`, `email` ) VALUES (?, ?, ?)";
    $stmt = $connection->prepare( $sql );

    if( $stmt ){
        /* if there were no problems continue with the database operations */
        $stmt->bind_param('sss', $username, $hash, $email );

        /* not sure how the hash was generated so just put this in to be sure... */
        $hash = password_hash( $password, PASSWORD_BCRYPT );

        $result = $stmt->execute();
        $stmt->free_result();
        $stmt->close();

        if( $result ){
            $_SESSION['username'] = $username;
            exit( header( 'Location: login.php' ) );
        } else {
            throw new Exception('Bogus! There was some sort of problem...');
        }
    } else {
        throw new Exception('Failed to prepare sql query');
    }
}catch( Exception $e ){
    exit( $e->getMessage() );
}

【讨论】:

  • 为什么我需要在这段代码之前调用 session_start(),因为它只是注册页面?
  • 因为你打电话给$_SESSION['username'] = $username;
猜你喜欢
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2012-11-13
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多