Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created July 29, 2020 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayfer/88c05716d1280fe3bf7af2b4666e7c93 to your computer and use it in GitHub Desktop.
Save mayfer/88c05716d1280fe3bf7af2b4666e7c93 to your computer and use it in GitHub Desktop.
The following is a simple HTML registration form:
<form action="register.php" method="post">
<p>
<label for="firstname">First Name:</label>
<input type="text" name="firstname" id="firstname" />
</p>
<p>
<label for="lastname">Last Name:</label>
<input type="text" name="lastname" id="lastname" />
</p>
<p>
<label for="email">Email Address:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<label for="password_confirm">Confirm Password:</label>
<input type="password" name="password_confirm" id="password_confirm" />
</p>
<p>
<input type="submit" value="Register" />
</p>
</form>
The form is submitted to the register.php script, which is shown in Example 10-1.
Example 10-1. register.php: processing a form
<?php
// Connect to the database
$db = new mysqli('localhost', 'fred', 'shhh', 'bigsales');
// Check that the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get the values from the form
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$password_confirm = $_POST['password_confirm'];
// Check that the form has been submitted correctly
if (empty($firstname) || empty($lastname) ||
empty($email) || empty($password) ||
empty($password_confirm)) {
// If the form has been submitted incorrectly,
// redirect the user to the form
header('Location: register.php');
exit;
}
// Check that the user hasn't already registered
$query = "SELECT * FROM users WHERE email = '$email'";
$result = $db->query($query);
if ($result->num_rows > 0) {
// If the user has already registered,
// redirect the user to the home page
header('Location: index.php');
exit;
}
// Register the user
$query = "INSERT INTO users (firstname, lastname, email,
password, password_confirm) VALUES ('$firstname', '$lastname',
'$email', '$password', '$password_confirm')";
$result = $db->query($query);
if ($result->affected_rows > 0) {
// The user has been registered
echo '<p>You have been registered successfully.</p>';
} else {
// There was a problem registering the user
echo '<p>There was a problem registering you.</p>';
}
} else {
// If the form hasn't been submitted,
// display the form
echo '<form action="register.php" method="post">
<p>First Name: <input type="text" name="firstname" id="firstname" /></p>
<p>Last Name: <input type="text" name="lastname" id="lastname"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment