SophiYo

Untitled

Jul 14th, 2019
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.65 KB | None | 0 0
  1. <?php
  2.  
  3. session_start();
  4.  
  5. //initializing variables
  6.  
  7. $username = "";
  8. $email = "";
  9.  
  10. $errors = array();
  11.  
  12. // connect to db
  13.  
  14. $db = mysqli_connect('localhost','root','', 'practice') or die( "could not connect to database");
  15.  
  16.  
  17. // register users
  18.  
  19. $username = mysqli_real_escape_string($db, $_POST['username']);
  20. $email = mysqli_real_escape_string($db, $_POST['email']);
  21. $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  22. $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
  23.  
  24.  
  25. // form validation
  26.  
  27. if(empty($username)) { array_push($errors, "Username is required") };
  28. if(empty($email)) { array_push($errors, "Email is required") };
  29. if(empty($password_1)) { array_push($errors, "Password is required") };
  30. if(password_1 != password_2) { array_push($errors, "Passwords do not match") };
  31.  
  32.  
  33. // check db for existing user with same username
  34.  
  35. $user_check_query = " SELECT * FROM user WHERE username = '$username' or email = '$email' LIMIT 1 ";
  36.  
  37.  
  38. $results = mysqli_query($db, $user_check_query);
  39. $user = mysqli_fetch_assoc($results);
  40.  
  41. if ($user) {
  42.    
  43. if ($user['username'] === $username) {array_push($errors, "Username already exists");}
  44. if ($user['email'] === $username) {array_push($errors, "this email is already in use");}
  45.  
  46. };
  47.  
  48. // Register the user if no error
  49.  
  50. if (count($errors) == 0) {
  51.     $password = md5($password_1); // this will encrypt the password
  52.     $query = "INSERT INTO user (username, email, password) VALUES ('$username', '$email', '$password') ";
  53.     mysql_query($db,$query);
  54.     $_SESSION['username'] = $username;
  55.     $_SESSION['success'] = "You are now logged in";
  56.     header('location: index.php');
  57.  
  58. };
  59.  
  60.  
  61.  ?>
Advertisement
Add Comment
Please, Sign In to add comment