我一直试图让它工作,当我点击其中一个或两个字段上的3个字符以下注册时,它不会弹出一个框,说明它应该说什么,当我点击上面注册时三者都不会给出确认或错误,更不用说将信息插入数据库了。
<?php
$sqlHost = 'localhost';
$sqlUser = 'root';
$sqlPass = 'hidthepassword';
$sqlDatabase = 'RPG';
$connection = new PDO('mysql:host='.$sqlHost.';dbname='.$sqlDatabase.';charset=utf8', $sqlUser, $sqlPass);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = null;
$password = null;
if(isset($_GET['user'])) {
$username = $_GET['user'];
}
if(isset($_GET['pass'])) {
$pass = $_GET['pass'];
}
if((isset($username)) && (isset($password))) {
// TODO SQL
$salt = genSalt(40);
$passHash = md5(md5($salt) . md5($password));
$statement = $connection->prepare("INSERT INTO `rpg`.`accounts` (`id`, `username`, `password`, `salt`) VALUES (:user, :pass, :salt);");
$statement->bindParam(":user", $username);
$statement->bindParam(":pass", $passHash);
$statement->bindParam(":salt", $salt);
if($statement->execute()) {
echo "Thank-you for your registration, " . $username;
} else {
echo "Sorry, your registration failed.";
}
} else {
// DISPLAY
echo '<input type="text" id="user" placeholder="username"/>
<input type="text" id="pass" placeholder="password"/>
<button id="button">Register</button>
<script>
var r = document.getElementById("button");
button.addEventListener("click", function() {
var user = document.getElementById("user");
var pass = document.getElementById("pass");
if(user.value.length < 3 || pass.value.length < 3) {
alert("Please enter a valid username or password");
} else {
window.location = "index.php?user="user.value+"&pass="+pass.value;
}
));
</script>
';
}
function genSalt($length) {
$variables = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789";
$charLength = strlen($variables);
$returned = "";
for($i = 0; $i < $length; $i++) {
$returned .= $variables[rand(0, ($charLength - 1))];
}
return $returned;
}
?>
答案 0 :(得分:3)
您将按钮定义为r
var r = document.getElementById("button");
然后将事件侦听器绑定到名为button
的var:
button.addEventListener("click", function()
在您的情况下应为r
。
此外,您应该使用POST而不是GET(或者对您的应用程序/数据库/等进行更改的任何内容)
答案 1 :(得分:0)
这里有一些错误:
首先,在PHP中,您从$password
切换到$pass
。所以解决这个问题:
if (isset($_GET['pass'])) {
$password = $_GET['pass']; // was $pass = $_GET['pass'];
}
在JavaScript中,我发现您的addEventListener
代码有3个错误:
r
切换到button
,您打算使用相同的参考。user.value
连接到位置字符串。最终结果:
// was var r = ...
var button = document.getElementById("button");
button.addEventListener("click", function () {
var user = document.getElementById("user");
var pass = document.getElementById("pass");
if (user.value.length < 3 || pass.value.length < 3) {
alert("Please enter a valid username or password");
} else {
// was "index.php?"user.value ...
window.location = "index.php?user="+user.value+"&pass="+pass.value;
}
}); // was ));