When I click on Register I always get both error messages: Registration successful! and Registration failed :/.
I've summarized the errors in this Errors.php file:
<?php if(count($errors) > 0): ?>
<div class="error">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
I can't figure out why mysqli_query($link, $sql)
doesn't run properly.
Code
<?php
//========================================
// Default values. Used for error messages
//========================================
$Email = "";
$errors = array();
//===============
// MySQL Settings
//===============
define('DB_NAME', 'registration');
define('DB_USER', 'root');
define('DB_PASSWORD', '12345678');
define('DB_HOST', 'localhost');
//====================
// Database connection
//====================
//Connect to server
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//===================================
// If the Register button is clicked
//===================================
if(isset($_POST['Register'])) {
$Email = mysqli_real_escape_string($_POST['Email']);
$Password = mysqli_real_escape_string($_POST['Password']);
//=================================
// Error messages if input is wrong
//=================================
if(empty($Email)) {
array_push($errors, "Email is required");
}
if(empty($Password)) {
array_push($errors, "Password is required");
}
//=========================
// Send data to MySQL table
//=========================
// Send input form data to MySQL database
if(isset($_POST['Register'])){
$Email = $_POST['Email'];
$Password = $_POST['Password'];
// If no error messages appear, then send data to table
if(count($errors) == 0){
$Password = md5($Password);
$sql = "INSERT INTO users (Email, Password) VALUES ('{$Email}', '{$Password}')";
}
$result = mysqli_query($link, $sql);
if ($result) {
// Success
echo "Registration successful!";
} else {
// Failure
echo "Registration failed :/";
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="Register.php">
<!--Display errror messages here-->
<?php include('Errors.php'); ?>
<div class="input-group">
<label>Email</label>
<input type="text" name="Email">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="Password">
</div>
<div class="input-group">
<button type="submit" id="button" name="Register" class="Button">Register</button>
</div>
<p>
Already a member? <a href="Login.php">Sign in</a>
</p>
</form>
</body>
</html>
<?php
// Close database connection
if (isset($link)) {
mysqli_close($link);
}
?>