Ниже приведен упрощенный код, который вы даже можете повторно использовать любое количество раз для любого количества проектов, просто просто редактируя значения базы данных.
Ниже приведено описание вашего db.php file
<?php
function db_connect() {
$link = @mysqli_connect ('localhost', 'username', 'password', 'table_name');
if (mysqli_connect_errno())
die ('Failed to connect to server.');
return $link;
}
?>
Этот файл теперь можно просто вызвать в любом формате .php. В вашем случае это скрипт регистрации. До этого ниже должен быть ваш HTML.
<form action="signup.php" method="POST">
<label>Pick a username: </label><input type="text" name="username" /> <br>
//Note that I have added "ID" to Password and Verify Password. This will be used to match the passwords before even submit.
<label>Pick a password: </label><input type="password" id="password" name="password" /> <br>
<label>Verify password: </label><input type="password" id="verify_password" name="verify_password" /> <br>
<label>Email address: </label><input type="text" name="email" /> <br>
//Note that I have added "Name" to the Button. This will be used in the sign-up script for validation. The script is called by onclick where Javascript fucntion is called.
<button name="singup-details" type="submit" onclick="registerFunction()">Sign Up</button>
</form>
Рекомендуется использовать пароли через Javascript, а не в скрипте регистрации PHP. Это не позволяет пользователю отправить форму в случае, если пароли не совпадают.
Ниже приведен код Javascript, который вы можете пропустить непосредственно перед тегом </body>
.
<script type="text/javascript">
//This will set passwordmatch variable on password and verify_password change.
$('#password, #verify_password').on('keyup', function() {
if ($('#password').val() == $('#verify_password').val()) {
$('#message').html('').css('color', 'green');
passwordmatch = 'yes';
} else {
$('#message').html(' Enter the Password again. Both the fields must match.').css('color', 'red');
passwordmatch = 'no';
}
});
//If password matches, it will prompt to ensure that if the entries are correct. Or else, will set the focus to Password field.
function registerFunction() {
if (passwordmatch == 'yes') {
if (confirm('You are about to change your password.\nPress OK to proceed.')) return false;
$("#userpassword").focus();
$("#userpassword").select();
event.preventDefault();
} else {
alert('Password do not match. Please check and try again.');
$("#userpassword").focus();
$("#userpassword").select();
event.preventDefault();
}
}
</script>
Теперь, наконец, ваш signup.php, который необходимо изменить.
<?php
session_start();
ob_start();
//You can set timezone in order if you plan to store the registration time as well.
date_default_timezone_set('Asia/Dubai');
include 'db.php';
$username = $_POST['useremail'];
$password = $_POST['password'];
$email = $_POST['email'];
//Saving the password directly is not safe. It is better to encrypt it using, at least, SHA1. Below is the way to encrypt the password.
$password = sha1($_POST['userpassword']);
//By checking isset $_POST of the singup button of HTML using its name value, we ensure that the user can browse this page only by filling in the Singup form or else will be sent back to the Signup form.
if (isset($_POST['singup-details'])) {
//This is the way you can check that if the user exists or not.
$sql = "SELECT * FROM your_table WHERE email = '" . $email . "'";
$result = mysqli_query(db_connect(), $sql);
$num_row = mysqli_num_rows($result);
if($num_row >= 1) {
//If username exists, it will take back to the singup form.
?>
<script language="javascript" type="text/javascript">
alert('<?php echo $username; ?> already exists in our records.\nTry Again.');
window.location = 'your_signup_form.php';
</script>
<?php
}
else {
//If username doesn't exist it will save it into the database. Also note that you do not have to save the Verify Password. It is not required at all.
$sql1 = "INSERT INTO table_name (username, email, password)
VALUES ('$username', '$email', '$password')";
$result1 = mysqli_query (db_connect(), $sql1);
?>
<script language="javascript" type="text/javascript">
alert('Thank you <?php echo $username; ?> for registering.');
window.location = 'any_page_you_want.php';
</script>
<?php
}
}
else {
//In case someone tries to access this page directly, this will take him to the singup page instead.
?>
<script language="javascript" type="text/javascript">
window.location = 'your_signup_form.php';
</script>
<?php
}
?>
Надеюсь, что это поможет. Счастливое кодирование ...
Где объявляется переменная $ link? – MCMXCII
Есть ли у вас ошибки? Можете ли вы подтвердить, что данные в db.php верны? –
Вы действительно не хотите делать встроенные скрипты sql таким образом. С вопросами по безопасности вы можете столкнуться. – rtrigoso