일자 : 24-2 13주차 2차시
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<!-- 사용자 입력을 받을 폼 -->
<form method="post" action="./2_form.php">
<!-- 이름을 입력받는 텍스트 박스 -->
Name: <input type="text" name="name">
<br><br>
<!-- 이메일을 입력받는 텍스트 박스 -->
E-mail: <input type="text" name="email">
<br><br>
<!-- 웹사이트를 입력받는 텍스트 박스 -->
Website: <input type="text" name="website">
<br><br>
<!-- 댓글을 입력받는 텍스트 영역 -->
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
<!-- 성별을 선택하는 라디오 버튼 -->
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<!-- 제출 버튼 -->
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
// 변수 선언 및 초기화
$name = $email = $gender = $comment = $website = "";
// 폼이 제출되었을 때 데이터 처리
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 입력된 데이터를 test_input 함수로 처리
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
// 입력 데이터를 안전하게 처리하는 함수
function test_input($data)
{
$data = trim($data); // 양옆 공백 제거
$data = stripslashes($data); // 이스케이프 문자 제거
$data = htmlspecialchars($data); // 특수 문자를 HTML 엔티티로 변환
return $data;
}
?>
<?php
// MySQL 데이터베이스 연결
$mysqli = mysqli_connect("localhost", "root", "", "myDB");
// 연결 확인
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
// 입력된 데이터를 데이터베이스에 삽입하는 SQL 쿼리
$sql = "INSERT INTO formtest (name, email, website, comment, gender) VALUES ('" . $_POST["name"] . "', '" . $_POST["email"] . "', '" . $_POST["website"] . "', '" . $_POST["comment"] . "', '" . $_POST["gender"] . "')";
$res = mysqli_query($mysqli, $sql);
// 삽입 성공 여부 확인
if ($res === TRUE) {
echo "A record has been inserted.";
} else {
printf("Could not insert record: %s\n", mysqli_error($mysqli));
}
mysqli_close($mysqli); // 데이터베이스 연결 종료
}
?>
<h2>PHP Form Validation Example Form Date </h2>
A record has been inserted.
<?php
// 입력된 데이터를 출력
echo "<h2>Your Input:</h2>";
echo $name; // 이름 출력
echo "<br>";
echo $email; // 이메일 출력
echo "<br>";
echo $website; // 웹사이트 출력
echo "<br>";
echo $comment; // 댓글 출력
echo "<br>";
echo $gender; // 성별 출력
?>
</body>
</html>


: 정상적으로 데이터가 잘 추가된 것을 볼 수 있다.
