PHP MYSQL데이터베이스 입력Database input

아래는 form6.php와 form_action6.php파일의 내용입니다.
이전에 다뤘던 내용과 많은 부분 일치합니다.
데이터 베이스 입력 부분만 살펴 보겠습니다.
데이터베이스는 MYSQL을 사용합니다.

Below are the contents of the form6.php and form_action6.php files.
This is largely consistent with what we covered previously.
Let’s only look at the database input part.
The database we will use is mysql.

1.MYSQL 로그인 LOGIN
new mysqli(“server host”,”username”,”password”,”databasename”); 이 부분이 MYSQL데이터 베이스에 로그인 하는 부분입니다.
new mysqli(“server host”,”user name”,”password”,”database name”); This is where you log in to the MYSQL database.

//mysql auth
$servername = "localhost";
$username = " ";
$password = " ";
$dbname = " ";

//connect mysql
$mysqli = new mysqli($servername,$username,$password,$dbname);

2.MYSQL ERROR CHECK
MYSQL로그인시 로그인이 실패하면 오류 메세지를 출력합니다.
When logging into MYSQL, if login fails, an error message is displayed.

   //mysql error check
   if ($mysqli->connect_errno) {
       printf("Connect failed: %s\n", $mysqli->connect_error);
       exit();
   }

3.MYSQL 자료 입력 Data input
정상적으로 자료입력이 되면 “New record created successfully” 메시지를 출력합니다.
입력실패시 오류 메시지를 출력합니다.
If data is entered normally, the message “New record created successfully” is displayed.
If input fails, an error message is output.


    $sql = "INSERT INTO testuser (name,email,title,website,pwd,comment) values('$f_name','$f_email','$f_title','$f_website','$f_pwd','$f_comment')";
    if($mysqli->query($sql)){
        echo "New record created successfully";
    }else{
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    };

4.COMMENT처리 부분[CREATE TABLE] ( COMMENT PART[CREATE TABLE])
테이블이 존재하지 않을 경우 생성하는 부분입니다.
필요시 COMMENT삭제하고 사용할 수 있습니다.

This is the part that creates the table if it does not exist.
If necessary, you can delete COMMENT and use it.

   /*
       ** create table **
       $sql = "CREATE TABLE IF NOT EXISTS testuser (
           id int(6) unsigned auto_increment primary key,
           name varchar(30) not null,
           email varchar(30) not null,
           title varchar(30) not null,
           website varchar(30) not null,
           pwd varchar(20) not null,
           comment text ); ";

        $mysqli->query($sql);
    */

5.COMMENT처리 부분-페이지 이동(COMMENT part – page movement)
데이터베이스자료 입력이 완료되면 페이지 이동합니다.
Once database data entry is complete, the page moves.

  // echo ("<script> window.location.href = './list.php'; </script> ");

6.전체코드(FULL CODE)

form6.php
<?php

$fileName = "./form_action6.php";

if(!is_file($fileName)){
    $form_action_name = basename($_SERVER['PHP_SELF']);
}else{
    $form_action_name = "./form_action6.php";
}
?>

<!DOCTYPE html>
<html>
    <head>
      <title>Bootstrap 5 webform</title>
      <!--이 부분은 html코멘트 영역 This part is the html comment area,마임타입설정 Mime type settings//-->
      <meta charset="utf-8">
      <!-- 모바일폰 스크린 옵션 Mobile phone screen options//-->
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <!--부트스트랩5 CDN방식 링크 Bootstrap 5 CDN method link//-->
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
      <!-- 폼체크 innerHTML경고 메시지 출력 -->
      <!-- Form check innerHTML warning message output //-->
      <script>
        function frmSubmit(){
            
           //name input box에서 값을 가져오기
           //Get value from name input box
           var frmName     = document.getElementById("name").value;
           var frmEmail    = document.getElementById("email").value;  
           var frmWebsite  = document.getElementById("website").value;     
           var frmTitle    = document.getElementById("title").value;                             
           var frmPwd      = document.getElementById("pwd").value;
           var frmComment  = document.getElementById("comment").value;

           //정규표현식과 비교하여 이메일 및 url테스트
           //Test the email and url against the regular expression
           var regex = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
           var emailCheck = regex.test(frmEmail); 
           var regexURL = /^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,7}(\/\S*)?$/i;
           var URLCheck = regexURL.test(frmWebsite);

           // 웹사이트주소가 공백이면 확인하지 않음.
           // If the website field is blank, it does not check.
           if(frmWebsite == ""){
            URLCheck = true;
           }           

           //에러메세지 초기화
           //Reset error message
           errorName.innerHTML = "";
           errorEmail.innerHTML = "";           
           errorPwd.innerHTML = "";
           errorWebsite.innerHTML = "";
           errorTitle.innerHTML = "";
           errorComment.innerHTML = "";
           
           //값의 존재 여부체크 ,공백이면 경고창 띄우기
           //Check whether value exists, if blank, display warning window
           if(frmName == ""){
            errorName.innerHTML ="<p>이름을 입력하세요(Please Enter Your Name)</p>";
            return;
           }else if(frmEmail == ""){
            errorEmail.innerHTML ="<p>Email을 입력하세요(Please Enter Your Email)</p>";
            return;
           }else if(emailCheck == false){   
            errorEmail.innerHTML ="<p>정확한 Email을 입력하세요(Please enter the correct Email)</p>";       
            return; 
           }else if(URLCheck == false){ 
            errorWebsite.innerHTML ="<p>정확한 URL을 입력하세요(Please enter the correct URL)</p>";       
            return; 
           }else if(frmTitle == ""){
            errorTitle.innerHTML ="<p>제목을 입력하세요(Please enter the post title)</p>";
            return;                                  
           }else if(frmPwd == ""){
            errorPwd.innerHTML ="<p>패스워드를 입력하세요(Please Enter Your Password)</p>";
            return;
           }else if(frmComment == ""){
            errorComment.innerHTML ="<p>글내용을 입력하세요(Please Enter The post content)</p>";
            return;            
           }else{
            frm.submit();
           }
        }
      </script>
    </head>
    <body>  
    <div class="container-sm">    
        <form id="frm" action="<?php echo $form_action_name; ?>" method="post">
        <div class="mb-3">
            <label for="name" class="form-label">이름(Name):</label>
            <input type="text" class="form-control" id="name" placeholder="당신의 이름을 입력하세요(Pleas enter your name)" name="name" required>
            <div id="errorName"></div>
        </div>

        <div class="mb-3">
        <label for="email" class="form-label">Email:</label>
            <input type="text" class="form-control" id="email" placeholder="ID@exmale.com" name="email" required>
            <div id="errorEmail"></div>
        </div>

        <div class="mb-3">
        <label for="website" class="form-label">Website:</label>
            <input type="text" class="form-control" id="website" placeholder="example.com" name="website">
            <div id="errorWebsite"></div> 
        </div>
        
        <div class="mb-3">
            <label for="pwd" class="form-label">Title:</label>
            <input type="text" class="form-control" id="title" placeholder="제목을 입력하세요(Please enter the post title)" name="title" required>
            <div id="errorTitle"></div>
        </div>

        <div class="mb-3">
            <label for="pwd" class="form-label">Password:</label>
            <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd" required>
            <div id="errorPwd"></div>
        </div>        

        <div class="mb-3">
            <label for="comment" class="form-label">Comment:</label>    
            <textarea id="comment"name="comment" rows="5" cols="40" class="form-control"></textarea>
            <div id="errorComment"></div>
        </div>

        <div class="mb-3">
            <div class="form-check mb-3">
            <label class="form-check-label">Remember me</label>
            <input class="form-check-input" type="checkbox" name="remember">
            </div>
        </div>
            <button type="button" class="btn btn-primary" onClick="frmSubmit();">Submit</button>
        </form>
    </div>    
    </body>
</html>   
form_action6.php

<?php  

if($_SERVER['REQUEST_METHOD'] == "POST"){

   $f_name = $_POST['name'];
   $f_pwd = $_POST['pswd'];
   $f_email = $_POST['email'];
   $f_title = $_POST['title'];
   $f_website = $_POST['website'];
   $f_comment = $_POST['comment'];

   // post data blank check
   if($f_name == ""){
    echo ("<script>
            alert('이름을 입력하세요(Please Enter Your Name).');
            window.location.href = './form5-1.php';
           </script>
        ");
    exit; 
   }else if($f_email == ""){ 
    echo ("<script>
           alert('Email을 입력하세요(Please Enter Your Email).');
           window.location.href = './form5-1.php';
           </script>
        ");
    exit;   
   }else if($f_title == ""){ 
    echo ("<script>
           alert('글 제목을 입력하세요(Please Enter Your Post Title).');
           window.location.href = './form5-1.php';
           </script>
        ");
    exit;                  
   }else if($f_comment == ""){
      echo ("<script>
              alert('글내용을 입력하세요(Please Enter The post content).');
              window.location.href = './form5-1.php';
             </script>
          ");
      exit;     
   }else if($f_pwd == ""){
    echo ("<script>
            alert('패스워드를 입력하세요(Please Enter Your Password).');
            window.location.href = './form5-1.php';
           </script>
        ");
    exit;    
   }   

   // email check
   if (!preg_match("/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/",$f_email)) {
      echo ("<script>
            alert('정확한 Email을 입력하세요(Please enter the correct Email).');
            window.location.href = './form5-1.php';
            </script>
         ");
       exit;
   }
   // URL check
    if ($f_website != "" && !preg_match("/^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,7}(\/\S*)?$/i",$f_website)) {
   echo ("<script>
         alert('정확한 URL을 입력하세요(Please enter the correct URL).');
         window.location.href = './form5-1.php';
         </script>
      ");
    exit;
   }

}

    // post data

   echo "REQUEST_METHOD:".$_SERVER['REQUEST_METHOD']."<br>";
   echo "이름(NAME):".$f_name."<br>";
   echo "이메일(EMAIL):".$f_email."<br>";
   echo "제목(TITLE):".$f_title."<br>";
   echo "웹사이트(WEBSITE):".$f_website."<br>";
   echo "글 내용(CONTENT):".$f_comment."<br>";
   echo "패스워드(PASSWORD):".$f_pwd;

   //mysql auth
   $servername = "localhost";
   $username = " ";
   $password = " ";
   $dbname = " ";
 
   //connect mysql
   $mysqli = new mysqli($servername,$username,$password,$dbname);
 
   //mysql error check
   if ($mysqli->connect_errno) {
       printf("Connect failed: %s\n", $mysqli->connect_error);
       exit();
   }

   /*
       ** create table **
       $sql = "CREATE TABLE IF NOT EXISTS testuser (
           id int(6) unsigned auto_increment primary key,
           name varchar(30) not null,
           email varchar(30) not null,
           title varchar(30) not null,
           website varchar(30) not null,
           pwd varchar(20) not null,
           comment text ); ";

        $mysqli->query($sql);
    */

    $sql = "INSERT INTO testuser (name,email,title,website,pwd,comment) values('$f_name','$f_email','$f_title','$f_website','$f_pwd','$f_comment')";
    if($mysqli->query($sql)){
        echo "New record created successfully";
    }else{
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    };

   // echo ("<script> window.location.href = './list.php'; </script> ");

?>

영상에 사용된 sql명령어(sql command used in video)

mysql log in : mysql -u mysqlID -p mysql database name;
테이블보기 : show tables;
테이블 구조보기(View table structure) : desc tablename;
최신 데이터 1개만 검색(Search for only 1 recent data) : select * from <tablename> order by <primary key> desc limit 1;

Leave a Reply

Your email address will not be published. Required fields are marked *