Good afternoon community,
I am currently reviewing some concepts of html, php, css, mysql, and I have been building a simple login system with a registration form, through some videos. So far so good, taking the time when I managed to register two customers with the same username. I spent a few hours in searches and tried to change my code, but I was never able to build a function to check if a client with the same name already exists in the database.
If someone can point me in the right direction for me to verify, I am grateful.
This is the code that treats everything about the server:
<?php
session_start();
$username = "";
$email = "";
$errors = array();
//liga à base de dados
$db = mysqli_connect("localhost", "root", "root", "mobies");
//se o botão de registar for clicado
if (isset($_POST['register'])){
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password_1 = mysql_real_escape_string($_POST['password_1']);
$password_2 = mysql_real_escape_string($_POST['password_2']);
//faz com que os espaços estejam bem preenchidos
if (empty($username)){
array_push($errors, "Username is required");
}
if (empty($email)){
array_push($errors, "Email is required");
}
if (empty($password_1)){
array_push($errors, "Password is required");
}
if ($password_1 != $password_2){
array_push($errors, "The two passwords do not match");
}
//se não houver erros, salva o novo utilizador na base de dados
if (count($errors) == 0) {
$password = md5($password_1);
$sql = "INSERT INTO utilizadores (username, email, password) VALUES ('$username', '$email', '$password')";
mysqli_query($db, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
//login através do formulário de login
if (isset($_POST['login'])){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//faz com que os espaços estejam bem preenchidos
if (empty($username)){
array_push($errors, "Username is required");
}
if (empty($password)){
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM utilizadores WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 1){
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
} else {
array_push($errors, "Wrong username/password combination");
}
}
}
//logout
if (isset($_GET['logout'])){
session_destroy();
unset($_SESSION['username']);
header('location: login.php');
}
?>
Thank you:)