我需要为这个准备好的语句使用 $stmt = $conn->prepare 吗?

Do i need to use $stmt = $conn->prepare for this prepared statement?

我准备好的语句的当前语法不正确,其中我:(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");

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

编辑:

$密码=$_POST['password'];

$hashed_password = password_hash($密码, PASSWORD_DEFAULT);

我刚刚想到这可能是 password_hash 的不正确用法?

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

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

/*
    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() );
}