W2_H2_로그인 페이지 구현(2)

·2023년 4월 20일
0

노말틱 취업스터디

목록 보기
9/16
post-thumbnail

💻 로그인 기능 구현 - 몇 가지 기능 수정

1) 데이터 베이스 만들기

sudo mysql -u root -p

// 데이터 베이스 생성
CREATE DATABASE account;
use account;

// 테이블 생성
CREATE TABLE user(
    -> id CHAR(15) PRIMARY KEY,
    -> password CHAR(25) NOT NULL,
    -> name CHAR(10) NOT NULL,
    -> phone_number INT(11) NOT NULL,
    -> birthday INT(8) NOT NULL,
    -> email CHAR(30) NOT NULL
    -> );

SHOW TABLES;
+-------------------+
| Tables_in_account |
+-------------------+
| user              |
+-------------------+

// 실험값 넣어보기
INSERT INTO user VALUES('apple','sweet','KimHaeJu','01036803306','25031999','seaju2503@naver.com');
// 테이블 확인하기
SELECT*FROM user;
+-------+----------+----------+--------------+----------+---------------------+
| id    | password | name     | phone_number | birthday | email               |
+-------+----------+----------+--------------+----------+---------------------+
| apple | sweet    | KimHaeJu |   1036803306 | 25031999 | seaju2503@naver.com |
+-------+----------+----------+--------------+----------+-----------------

// 내용 바꾸기
UPDATE user SET name='KHJ',phone_number='01012345678' WHERE id='apple';
// 길이값 바꾸기
ALTER TABLE user MODIFY phone_number VARCHAR(12);

값을 전달할 account.php 파일 생성

<?php

// db와 연결하기
$conn = mysqli_connect("localhost","root","1231","account");

// 입력받은 값 전달 변수 생성
$email = $_POST["email"];
$name = $_POST["name"];
$id = $_POST["id"];
$password = $_POST["password"];
$phone_number = $_POST["phone"];
$birthday=$_POST["date"].$_POST["month"].$_POST["year"];

// 변수 전달이 제대로 되는지 확인하는 코드
#echo "<h3>inserting data is id{$id}, password{$password}, name{$name}, phone{$phone_number},birthday{$birthday}, email{$email}</h3>";

// DB에 입력받은 값 삽입하기
$sql="INSERT INTO user(id, password, name, phone_number,birthday, email)VALUES('$id','$password','$name','$phone_number','$birthday','$email')";

// DB에 제대로 입력값이 들어갔는지 통신 확인 코드 
if($conn->query($sql))echo "<h3> user account succeded! <h3>";
else echo "<h3> failed <h3>";

?>

Form 태그 수정

account.html 파일로 들어가 form 태그를 수정해준다.

<form action="account.php" method="post">

DB에 제대로 값이 입력되었는지 확인하기

SELECT*FROM user;
+-----------+----------+------+--------------+----------+---------------------+
| id        | password | name | phone_number | birthday | email               |
+-----------+----------+------+--------------+----------+---------------------+
| apple     | sweet    | KHJ  | 01012345678  | 25031999 | seaju2503@naver.com |
| shjee2217 | 1234     | EL   | 01062702217  | 29091999 | shjee2217           |
+-----------+----------+------+--------------+----------+---------------------+

로그인 시 id 값을 통해 user 식별하기

  • id 중복 확인을 위한 버튼 생성
// account.html 파일 수정
<div style="float:left; margin-right: 20px;"> <input type="text" name="id" id="id" maxlength="15" placeholder="id" required></div>
// id 식별 버튼 생성
<div style="float:left;"><button type="button" name="check_button" class="same_id_check" onclick="same_id_check()">ID DUPPLICATION CHECK</button></div>

<label style="clear:left;" for="password">PASSWORD : </label>
  • 버튼을 눌렀을 시 id 중복 확인 코드
<script type="text/javascript">
    function same_id_check() {
        var id_input = document.getElementById('id').value; 

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var result = this.responseText;
                if (result == 'unavailable') {
                    alert('THIS USER ID IS UNAVAILABLE!');
                } else {
                    alert('You can use this id!');
                }
            }
        };
        xhttp.open('GET', 'check_id.php?id=' + id_input, true);
        xhttp.send();
    }
</script>


  • submit 버튼을 눌렀을 때 id가 중복되면 id 중복체크를 하라고 경고하고, 다시 register 페이지로 돌아가기
$check_sql = "SELECT id FROM user WHERE id='$id'";
$result = mysqli_query($conn, $check_sql);

// id값 중복 확인하기
if (mysqli_num_rows($result) > 0) {
		// id값이 중복되면 계정 생성 페이지로 다시 돌아가기
        echo "<script>alert('Your id is not available! Please check and change your id.');</script>";
        echo "<script>window.location.href='account.html';</script>";
    exit();
}

// 중복되는 id 값이 없다면 입력된 정보를 db에 저장하고, 로그인 화면으로 넘어감
else {
    $insert_sql = "INSERT INTO user(id, password, name, phone_number, birthday, email)VALUES('$id','$password','$name','$phone_number','$birthday','$email')";

    if($conn->query($insert_sql)){
        echo "<script>alert('ID successfully created!');</script>";
        echo "<script>window.location.href='login1.html';</script>";
    } else {
        echo "<h3>Failed</h3>";
    }
}

mysqli_close($conn);

로그인 과정 수정

db에서 값을 받아와 사용자의 input 값의 id와 password 값을 비교하고, 그 값이 맞다면 main.php 파일로 넘어가기

<?php
session_start();

if (isset($_POST['loginBtn'])) {
    $username = $_POST['id'];
    $password = $_POST['psw'];

    $conn = mysqli_connect("localhost","root","1231","account");
    $sql = "SELECT*FROM user WHERE id='$username' AND password='$password'";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result)>0) {
        $_SESSION['userid'] = $username;
        header("Location: main.php");
        exit();
    } else {
        echo "<script>alert('Login Failed!');
        location.href='login1.html'</script>";
    }
}
?>


✍🏻 다음 수정사항

  • submit 버튼을 눌렀을 때 입력된 정보가 날라가지 않도록 그 화면에서 alert 만 출력되도록 바꾸기
  • e-mail 값에 select로 고른값이 함께 db에 저장되어야 함
  • password 값과 check your password 값을 비교하여 두 값이 일치하지 않을 시, 'your password is not matched!' 문구 출력
  • birthday 부분 범위 지정하기
    date : 1 ~ 31
    month : 1 ~ 12
    year : 1900 ~ 2023

🤍 참조

profile
화이트해커 꿈나무 엘입니다😉

0개의 댓글

관련 채용 정보