Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- session_start();
- //initialising variables
- $username = "";
- $email = "";
- $errors = array();
- //connect to db
- $db = mysqli_connect('localhost','root','','practice') or die("couldn't connect to the db");
- //Register users
- if (isset($_POST['reg_user'])) {
- // Receive all input values from the form
- $username = mysqli_real_escape_string($db, $_POST['username']);
- $email = mysqli_real_escape_string($db, $_POST['email']);
- $password_a = mysqli_real_escape_string($db, $_POST['password_a']);
- $password_b = mysqli_real_escape_string($db, $_POST['password_b']);
- //form validation : ensure that the form is correctly filled...
- // by adding (array_push()) corresponding error onto $errors array
- if(empty($username))
- {
- array_push($errors, "username is required!");
- }
- if(empty($email))
- {
- array_push($errors, "email is required!");
- }
- if(empty($password_a))
- {
- array_push($errors, "password is required!");
- }
- if($password_a != $password_b)
- {
- array_push($errors, "Password don't match!");
- }
- // first check the database to make sure
- // a user does not already exits with the same username and/or email
- $user_check_query = "SELECT * FROM user WHERE username = `$username` or email = `$email` LIMIT 1";
- $result = mysqli_query($db, $user_check_query);
- $user = mysqli_fetch_assoc($result);
- if($user) { // if user exist
- if($user['username'] === $username)
- {
- array_push($errors, "Username already exists");
- }
- if($user['email'] === $email)
- {
- array_push($errors, "Email already exists");
- }
- }
- // Finally, Register the user if there is no error in the form
- if(count($errors) == 0 ){
- $password = md5($password_a); // Encrypt the password before saving in the database
- $query = "INSERT INTO user (username, email, password) VALUES ('$username','$email','$password')";
- mysqli_query($db,$query);
- $_SESSION['username'] = $username;
- $_SESSION['success'] = "You are now logged in";
- }
- header("location: index.php);
- }
- ?>
Add Comment
Please, Sign In to add comment