Reputation: 11
I am trying to make a registration system with php and mysql. I am attempting to connect the database to the system and am getting errors which I do not understand.
I am relatively new to both php and my sql so any advice would be great.
Upvotes: 1
Views: 43
Reputation: 151
For example:
generatesalt.php (optional, for safety)
function generateSalt()
{
$salt = '';
$saltLength = 8;
for($i=0; $i<$saltLength; $i++) {
$salt .= chr(mt_rand(33,126)); //character from ASCII-table
}
return $salt;
}
db.php
$dbname = 'test';
$localhost = 'localhost';
$login = 'root';
$pass = '';
$link = @mysqli_connect($localhost, $login, $pass, $dbname);
if (!$link) {
echo "Problem, error code: " . mysqli_connect_errno();
exit;
}
reg.php (This example is not very secure. I advise you to use PDO. This is an easy example for understanding.)
require_once 'db.php';
require_once 'generateSalt.php';
if ( !empty($_POST['login']) and !empty($_POST['password']) and !empty($_POST['password_confirm']) ) {
$login = $_POST['login'];
$password = $_POST['password'];
$password_confirm = $_POST['password_confirm'];
if ($password == $password_confirm) {
$query = 'SELECT*FROM user WHERE login="'.$login.'"';
$is_login_free = mysqli_query($link, $query);
$login_free = mysqli_fetch_assoc($is_login_free);
if (empty( $login_free)) {
$salt = generateSalt();
$saltedpassword = md5($password.$salt);
$query = "INSERT INTO `user` (`login`, `password`, `salt`) VALUES ('$login', '$saltedpassword', '$salt')";
$result = mysqli_query($link, $query);
echo 'You have successfully registered';
echo '<br>';
echo 'Sign in: <a href="/login.php">Click</a>';
echo '<br>';
echo 'Home: <a href="/">Click</a>';
} else {
echo 'The login is busy';
}
} else {
echo 'Passwords do not match';
}
} else {
header("Location: /");
exit();
}
Form
<h1>Sign up</h1>
<form action="/reg.php" method="post">
<input type="text" name="login" required><br>
<input type="password" name="password" required><br>
<input type="password" name="password_confirm" required><br><br>
<input type="submit" value="Create an account">
</form>
Upvotes: 3