gpt4 book ai didi

javascript - 而不是错误地使用 die

转载 作者:行者123 更新时间:2023-11-29 08:07:15 28 4
gpt4 key购买 nike

我目前正在制作一个注册页面。它包括密码散列和验证。当我使用“die”时,它会停止表单并显示错误。我想在同一页面上显示错误。

<?php 

// First we execute our common code to connection to the database and start the session
require("common.php");

$ErrorTest ="";
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
$ErrorTest = "Please enter a username.";
}

if(empty($_POST['password']))
{
$ErrorTest = "Please enter a password.";
}

if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$ErrorTest = "Invalid E-Mail Address";
}

$query = "
SELECT
1
FROM users
WHERE
username = :username
";


$query_params = array(
':username' => $_POST['username']
);

try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest = "Failed to run query: " . $ex->getMessage();
}
$row = $stmt->fetch();

if($row)
{
$ErrorTest = "This email address is already registered";
}

$query = "
SELECT
1
FROM users
WHERE
email = :email
";

$query_params = array(
':email' => $_POST['email']
);

try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest ="Failed to run query: " . $ex->getMessage();
}

$row = $stmt->fetch();

if($row)
{
$ErrorTest = "This username is already in use";
}

$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));


$password = hash('sha256', $_POST['password'] . $salt);

{
$password = hash('sha256', $password . $salt);
}

$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);

try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest = "Failed to run query: " . $ex->getMessage();
}

// This redirects the user back to the login page after they register
header("Location: myprofile.php");
$ErrorTest = "Redirecting to admin_login.php";
}

?>

die(“请输入用户名”) 我想将其显示在同一页面上。我还尝试将其放在 JavaScript 上,但是当我在一个文本框中输入错误信息时,它会弹出所有错误并显示查询。

最佳答案

我的方法是将 die 替换为对 $error 的变量赋值

die("Failed to run query: " . $ex->getMessage());

替换为

$error = ("Failed to run query: " . $ex->getMessage());

然后用条件语句包装您的注册逻辑,检查是否已设置或是否为空(由您决定)

然后您可以在表单上使用 echo 输出此消息。

编辑

当您重定向到另一个页面而不是在同一页面上处理时,请将代码调整为

if($ErrorTest != ''){
header("位置:register.php?error=".$ErrorTest);
}
别的{
header("位置:myprofile.php");
}

在register.php页面只需检查$_GET['error']然后输出它。

即使出现错误,您也始终会注册用户,因此可能值得将此代码添加到“else”中

关于javascript - 而不是错误地使用 die,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22460605/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com