사자자리
[PHP & MySQL] 웹페이지에 입력한 데이터를 테이블에 추가하기 본문
웹페이지에 입력한 데이터를 테이블에 추가하기: INSERT
1. index.php에 create 링크(create.php) 생성
<!--htdocs\index.php-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<li>HTML</li>
</ol>
<a href="create.php">create</a> <!--글쓰기 기능 링크-->
<h2>Welcome</h2>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</body>
</html>
2. create.php 파일 생성: title 입력 박스, description 입력 박스 생성
<!--htdocs\create.php-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<li>HTML</li>
</ol>
<form action="process_create.php" method="post">
<p><input type="text" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p><input type="submit"></p>
</form>
</body>
</html>
3. process_create.php 파일에서 입력받은 데이터를 mysql에 전송
<!--htdoc\process_create.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '******', 'opentutorials'); //데이터베이스 서버에 접속
$sql="
INSERT INTO topic(title, description, created)
VALUES('{$_POST['title']}', '{$_POST['description']}', NOW())
"; //create.php에서 입력받은 데이터 값으로 sql문 작성
$result = mysqli_query($conn, $sql);
if($result === false){
echo "ERROR";
error_log(mysqli_query($conn));
}
else {
echo "성공했습니다.\n<a href=\"index.php\">BACK TO PAGE</a>";
}
?>
4. 실습
MariaDB [opentutorials]> SELECT * FROM topic;
+----+------------+-------------------+---------------------+
| id | title | description | created |
+----+------------+-------------------+---------------------+
| 1 | MySQL | MySQL is ... | 2022-08-01 22:33:48 |
| 2 | SQL Server | SQL Server is ... | 2022-08-01 23:09:43 |
+----+------------+-------------------+---------------------+
2 rows in set (0.000 sec)
'웹기초 > 생활코딩 WEB 3 - PHP & MySQL' 카테고리의 다른 글
[PHP & MySQL] DELETE (0) | 2022.08.07 |
---|---|
[PHP & MySQL] UPDATE (0) | 2022.08.07 |
[PHP & MySQL] 보안: Filtering & Escaping (0) | 2022.08.03 |
[PHP & MySQL] 테이블에서 데이터를 가져와서 PHP에서 활용하기 (0) | 2022.08.03 |
[PHP & MySQL] PHP와 MySQL의 연동 (0) | 2022.08.02 |
Comments