댓글 검색 목록

[php] HTML 양식에서 배열을 게시하는 방법

페이지 정보

작성자 운영자 작성일 20-04-20 11:00 조회 1,035 댓글 0

HTML 형식으로 배열을 게시하고 PHP에서 데이터를 처리하는 방법에 대한 자습서에 오신 것을 환영합니다. 

HTML 형식으로 데이터를 처리하는 것은 쉽습니다. 입력 필드 나 텍스트 상자에 이름 속성을 추가하기 만하면 됩니다. 

그러나 대신 배열을 게시하려면 어떻게 해야 합니까? 간단히 말해서 – HTML 양식에서 배열을 게시하려면 입력 필드의 이름 속성 끝에 대괄호 쌍을 추가하기 만하면 됩니다. 

예를 들면 <input name =”favorites []”type =”text”>입니다.


그러나 Javascript 에서 이 작업을 수행하는 것은 어떻습니까? 다차원 배열은 어떻습니까? 

PHP에서 포스트 데이터를 어떻게 처리합니까? 이것이 본 안내서에서 예를 통해 살펴볼 것입니다. 알아 보려면 계속 읽으십시오!


ⓘ이 튜토리얼을 시작할 때 모든 예제 소스 코드가 포함 된 zip 파일을 포함 시켰으므로 모든 내용을 복사하여 붙여 넣을 필요가 없습니다.


다운로드 


먼저 약속 된 예제 소스 코드에 대한 다운로드 링크가 있습니다.


소스 코드 다운로드 


소스 코드를 다운로드하려면 여기를 클릭하십시오. MIT 라이센스에 따라 릴리스되었으므로 그 위에 빌드하거나 자신의 프로젝트에서 자유롭게 사용하십시오.


빠른 시작 


  • 폴더에 다운로드하여 압축을 풉니다.
  • 관련된 데이터베이스가 없으므로 포함 된 각 파일을 따라 가십시오.

기본 


소화하기 쉬운 것으로 시작합시다 – 초보자를 위한 HTML 양식을 간단히 살펴보면, 이미 코드 닌자라면 이 섹션을 건너 뛰어도 됩니다.


HTML 


<!DOCTYPE html> <html> <head> <title> Basic HTML Form </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> </head> <body> <form method="post" action="1b-server.php"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <input type="submit" value="Submit"/> </form> </body> </html> 


  • 구조에 명백한 선장! HTML로 양식을 만들려면 <form> 태그를 사용합니다.
  • <form> 제출 방법은 게시하거나 가져올 수 있습니다.
    get은 쿼리 문자열로 양식 데이터를 URL에 추가합니다. 예 : http://mysite.com/submit.php?name=John+Doe
    post는“자동”이며 쿼리 문자열에 데이터를 추가하지 않습니다.
  • <form>의 action 속성은 양식을 제출할 서버 측 스크립트를 정의합니다.
  • <form> 안에 <input> 필드를 끼워 사용자 데이터 입력을 수집합니다.
  • <input> 필드에 이름 속성을 지정하면 $ _POST superglobal 변수의 키가됩니다. 예를 들어, <input name = "user-email">을 제출하면 $ _POST [ 'user-email']을 사용하여 PHP에서 값을 얻을 수 있습니다.


서버 측 PHP 


<?php // The $_POST superglobal variable will contain all the form data // Just dump it if you need to debug and see what is being submitted print_r($_POST); echo "<br><br>"; // $_POST is an array. // We can easily retrieve the submitted form data with: // $_POST['user-name'] contains the name echo "USER NAME: " . $_POST['user-name'] . "<br>"; // $_POST['user-email'] contains the email echo "USER EMAIL: " . $_POST['user-email'] . "<br>"; ?> 


형태의 배열 


이제 HTML 양식 기본 사항을 다뤘으므로 백만 달러짜리 질문 – HTML 양식으로 배열을 보내는 방법으로 넘어가겠습니다.


HTML 

<!DOCTYPE html> <html> <head> <title> HTML array in Form Demo </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> </head> <body> <form method="post" action="2b-server.php"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <!-- To send as an array, use square brackets in the name --> <label>Favorite Colors</label> <input type="text" name="user-color[]" required value="red"/> <input type="text" name="user-color[]" required value="green"/> <input type="text" name="user-color[]"/> <input type="submit" value="Submit"/> </form> </body> </html> 


네, 그렇게 어렵지는 않습니다.


  • 배열을 보내려면 단순히 이름 속성 끝에 대괄호 쌍을 추가하면 됩니다. 예를 들어, <input type = "text"name = "user-color []">입니다.
  • 필요한 이름과 동일한 <input> 필드를 추가하십시오. 위의 예에서 최대 3 개의 즐겨 찾는 색상을 캡처 할 수 있습니다.
  • 위의 예에서 필수 속성을 2 개의 필드에만 추가 할 수 있는 방법에 유의하십시오. 사용자는 최소한 두 개의 선호하는 색상을 입력해야 하며 세 번째는 선택 사항입니다.

SERVER-SIDE PHP 


<?php // For debugging - Dump if you want to see what is being submitted print_r($_POST); echo "<br><br>"; // You know this part... echo "USER NAME: " . $_POST['user-name'] . "<br>"; echo "USER EMAIL: " . $_POST['user-email'] . "<br>"; // This can be a little confusing for beginners. // $_POST is an array. $_POST['user-color'] is now an array within $_POST. echo "FAV COLORS: <br>"; foreach ($_POST['user-color'] as $color) { echo $color . "<br>"; } ?> 


다차원 배열 


다차원 배열을 원한다면 어떻게 해야 할까요? 배열 내에 배열을 게시하려면? 다음 단계로 넘어 갑시다.


HTML 


<!DOCTYPE html> <html> <head> <title> HTML array in Form Demo </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> </head> <body> <form method="post" action="3b-server.php"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <!-- We can define multi-dimensional form fields similar to arrays in PHP --> <!-- Use 2 square brackets, give the first one a key for better organization --> <label>Favorite Colors</label> <input type="text" name="user-fav[color][]" required value="red"/> <input type="text" name="user-fav[color][]" required value="green"/> <input type="text" name="user-fav[color][]"/> <label>Favorite Food</label> <input type="text" name="user-fav[food][]" required value="bacon"/> <input type="text" name="user-fav[food][]" required value="eggs"/> <input type="text" name="user-fav[food][]" value=""/> <input type="submit" value="Submit"/> </form> </body> </html> 


다차원 양식 필드도 그렇게 어렵지 않습니다. – 대괄호 2 개만 사용하고 첫 번째 키는 키를 제공하십시오. 그게 다야.


SERVER-SIDE PHP 


<?php // For debugging - Dump if you want to see what is being submitted print_r($_POST); echo "<br><br>"; // You know this part... echo "USER NAME: " . $_POST['user-name'] . "<br>"; echo "USER EMAIL: " . $_POST['user-email'] . "<br>"; // This can be a little more confusing for beginners. // $_POST['user-fav'] is now an array of array echo "FAV COLORS: <br>"; foreach ($_POST['user-fav']['color'] as $color) { echo $color . "<br>"; } echo "FAV FOOD: <br>"; foreach ($_POST['user-fav']['food'] as $food) { echo $food . "<br>"; } ?> 


AJAX ARRAY POST 


마지막으로 Javascript AJAX 호출을 통해 배열을 게시하는 방법을 살펴 보겠습니다.


HTML 


<!DOCTYPE html> <html> <head> <title> AJAX Array Demo </title> <style> /* [DOES NOT MATTER, JUST COSMETICS] */ form { font-family: arial, sans-serif; max-width: 300px; } label, input { display: block; width: 100%; margin: 5px 0; padding: 5px; box-sizing: border-box; } input[type=submit] { background: #305ba0; color: #fff; border: 0; margin-top: 10px; } </style> <script src="4b-form.js"></script> </head> <body> <form onsubmit="return save()"> <label>Name</label> <input type="text" name="user-name" required value="John Doe"/> <label>Email</label> <input type="email" name="user-email" required value="john@doe.com"/> <label>Address</label> <input type="text" name="user-addr[]" required value="Foo Street 123"/> <input type="text" name="user-addr[]" required value="Hello World 345"/> <label>Favorite Colors</label> <input type="text" name="user-fav[color][]" required value="red"/> <input type="text" name="user-fav[color][]" required value="green"/> <input type="text" name="user-fav[color][]"/> <label>Favorite Food</label> <input type="text" name="user-fav[food][]" required value="bacon"/> <input type="text" name="user-fav[food][]" required value="eggs"/> <input type="text" name="user-fav[food][]" value=""/> <input type="submit" value="Submit"/> </form> </body> </html> 


여기에는 큰 차이가 없습니다. 여전히 동일한 HTML 양식이지만 onsubmit = "return save"를 사용하여 Javascript가 대신 제출을 처리하도록 합니다.


JAVASCRIPT 


function save () { // (A) COLLECT FORM DATA var data = new FormData(); // These should be pretty straight forward data.append('user-name', document.getElementsByName("user-name")[0].value); data.append('user-email', document.getElementsByName("user-email")[0].value); // We do pretty much the same in Javascript for array fields // Add a pair of square brackets to the end of the name var fields = document.getElementsByName("user-addr[]"); for (var f of fields) { data.append('user-addr[]', f.value); } // Same for multi-dimensional arrays as well fields = document.getElementsByName("user-fav[color][]"); for (var f of fields) { data.append('user-fav[color][]', f.value); } fields = document.getElementsByName("user-fav[food][]"); for (var f of fields) { data.append('user-fav[food][]', f.value); } // (B) AJAX CALL var xhr = new XMLHttpRequest(); xhr.open('POST', "4c-server.php", true); // When the process is complete xhr.onload = function(){ console.log("Done"); console.log(this.response); alert("OK - See console for server response"); }; // Send xhr.send(data); return false; } 


처음에는 초보자에게는 약간 혼란스러워 보일 수 있지만 자세히 살펴보십시오.이 스크립트에는 두 부분 만 있습니다.


  • 첫 번째 부분에서는 단순히 양식 데이터를 수집하는 것입니다.
  • 그런 다음 AJAX 호출로 서버로 전송하십시오.

SERVER PHP 


<?php print_r($_POST); ?> 


여기서 볼 것이 없습니다. 제출되는 모든 내용을 반영하는 더미 스크립트입니다.


유용한 비트 


이것이 이 프로젝트의 전부이며, 여기에 도움이 될만한 추가 정보에 대한 작은 섹션이 있습니다.


INFOGRAPHICS CHEAT SHEET 


html-form-array-small.jpg 


참조 





댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.