php & mysql 연동원리
웹서버는 php 확장자 처리 불가능 -> php 프로그램이 php파일에 대한 처리 -> html 코드를 넘겨줌
php는 웹, 데이터베이스 연결 -> 미들웨어라고도 함
html & php 준비
index.php를 만들어준다.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<li>HTML</li>
</ol>
<h2>Welcome</h2>
Lorem ipsum dolor sit amet, consectetur adipisicing elit
</body>
</html>
데이터베이스를 생성하고 테이블을 생성해준다.
CREATE TABLE topic (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(45) NOT NULL,
description text,
created datetime NOT NULL,
PRIMARY KEY(id)
) ENGINE=InnoDB;
php client로서 mysql
실제 데이터가 저장된 mysql 서버를 제어하기 위해 mysql 모니터를 사용해왔음.
mysql 모니터는 mysql 서버에 대해 클라이언트이다.
php 역시 mysql 서버에 대해 클라이언트이다.
mysql api 찾기
PDO_mysql 추천.(다른 관계형 데이터베이스 사용시 교체 용이)
강의에선 Mysqli를 사용함 -> php mysqli api
php & mysql 연동
insert.php 내용을 변경해준다 (주석 참고)
<?php
/* mysql 서버에 연결
mysqli_connect(호스트, 유저이름, 비밀번호, 데이터베이스) */
$conn = mysqli_connect("localhost", "root", "111111", "opentutorials");
$sql = "
INSER INTO topic (
title,
description,
created
) VALUES (
'MySQL',
'MySQL is ....',
NOW()
)";
/* mysql 서버에 sql 문 전송*/
$result = mysqli_query($conn, $sql);
/* 문제가 발생했을 때(연결실패) 마지막 오류 설명 반환*/
if($result === false){
echo mysqli_error($conn);
}
?>
글 생성
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
</body>
</html>
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>
process_create,php
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
$sql = "
INSERT INTO topic
(title, description, created)
VALUES(
'{$_POST['title']}',
'{$_POST['description']}',
NOW()
)
";
$result = mysqli_query($conn, $sql);
if($result === false){
echo '저장하는 과정에서 문제가 생겼습니다. 관리자에게 문의해주세요';
error_log(mysqli_error($conn));
} else {
echo '성공했습니다. <a href="index.php">돌아가기</a>';
}
?>
실행결과
mysql 연동과 select 문
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
echo "<h1>single row</h1>";
$sql = "SELECT * FROM topic WHERE id = 19"; //select문
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result); //여러 행 가지고 오기(모든 행) (데이터를 php에서 사용하도록 전환)
echo '<h2>'.$row['title'].'</h2>';
echo $row['description'];
echo "<h1>multi row</h1>";
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)) { //더이상 가져올 행이 없을때까지
echo '<h2>'.$row['title'].'</h2>';
echo $row['description'];
}
글 읽기
index.php
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($result)) {
$list = $list."<li><a href=\"index.php?id={$row['id']}\">{$row['title']}</a></li>";
}
$article = array(
'title'=>'Welcome',
'description'=>'Hello, web'
);
if(isset($_GET['id'])) {
$sql = "SELECT * FROM topic WHERE id={$_GET['id']}";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$article['title'] = $row['title'];
$article['description'] = $row['description'];
}
?>
<!doctype html>
<html>
<head>
@@ -7,11 +22,7 @@
<body>
<h1>WEB</h1>
<h1><a href="index.php">WEB</a></h1>
<ol>
<?=$list?>
</ol>
<a href="create.php">create</a>
<h2>Welcome</h2>
Lorem ipsum dolor sit amet, consectetur adipisicing elit
<h2><?=$article['title']?></h2>
<?=$article['description']?>
</body>
</html>
create.php
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($result)) {
$list = $list."<li><a href=\"index.php?id={$row['id']}\">{$row['title']}</a></li>";
}
$article = array(
'title'=>'Welcome',
'description'=>'Hello, web'
);
if(isset($_GET['id'])) {
$sql = "SELECT * FROM topic WHERE id={$_GET['id']}";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$article['title'] = $row['title'];
$article['description'] = $row['description'];
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<h1><a href="index.php">WEB</a></h1>
<ol>
<li>HTML</li>
<?=$list?>
</ol>
<form action="process_create.php" method="POST">
<p><input type="text" name="title" placeholder="title"></p>
</form>
</body>
</html>
php, mysql 보안
입력 공격 차단
1) flitering - 들어오는 정보에서 문제가 있는 정보를 막는 것
sql injection의 차단
주석 ( -- ) -> 주석에 대해 처리된 데이터를 db 서버는 무시함
mysql_multi_query() : 복수의 sql을 실행, 하지만 보안 문제로 mysqli_query를 쓰는 것을 지향
die(): 들어온 값 출력과 동시에 프로그램 실행종료
위험성
- db의 다른 테이블 지울 수 있음
-새 유저 생성 및 권한 부여 가능
-sql server는 db를 통해 운영체제의 명령 가능 -> 서버컴퓨터 점령 가능
mysqli_real_escape_string(연결 객체, 문자열)
: sql injection과 관련된 여러가지 기호들을 문자로 바꾸는 함수
2) escaping - 무제가 있는 정보가 들어와 있는 상태에서 그 정보를 사용자에게 차단하는 것
xss의 차단
html에서 <>와 같은 특수문자를 그대로 표현
htmlspecialchars()
: <>와 같은 특수문자를 모두 변환하는 함수
글 수정 및 삭제
update.php
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($result)) {
$escaped_title = htmlspecialchars($row['title']);
$list = $list."<li><a href=\"index.php?id={$row['id']}\">{$escaped_title}</a></li>";
}
$article = array(
'title'=>'Welcome',
'description'=>'Hello, web'
);
$update_link = '';
if(isset($_GET['id'])) {
$filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
$sql = "SELECT * FROM topic WHERE id={$filtered_id}";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$article['title'] = htmlspecialchars($row['title']);
$article['description'] = htmlspecialchars($row['description']);
$update_link = '<a href="update.php?id='.$_GET['id'].'">update</a>';
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1><a href="index.php">WEB</a></h1>
<ol>
<?=$list?>
</ol>
<form action="process_update.php" method="POST">
<input type="hidden" name="id" value="<?=$_GET['id']?>">
<p><input type="text" name="title" placeholder="title" value="<?=$article['title']?>"></p>
<p><textarea name="description" placeholder="description"><?=$article['description']?></textarea></p>
<p><input type="submit"></p>
</form>
</body>
</html>
process_update.php
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
settype($_POST['id'], 'integer');
$filtered = array(
'id'=>mysqli_real_escape_string($conn, $_POST['id']),
'title'=>mysqli_real_escape_string($conn, $_POST['title']),
'description'=>mysqli_real_escape_string($conn, $_POST['description'])
);
//where - 어디에 수정 적용할지 set - 변수값이 반드시 정수
$sql = "
UPDATE topic
SET
title = '{$filtered['title']}',
description = '{$filtered['description']}'
WHERE
id = {$filtered['id']}
";
$result = mysqli_query($conn, $sql);
if($result === false){
echo '저장하는 과정에서 문제가 생겼습니다. 관리자에게 문의해주세요';
error_log(mysqli_error($conn));
} else {
echo '성공했습니다. <a href="index.php">돌아가기</a>';
}
?>
process_delete.php
<?php
$conn = mysqli_connect(
'localhost',
'root',
'111111',
'opentutorials');
settype($_POST['id'], 'integer');
$filtered = array(
'id'=>mysqli_real_escape_string($conn, $_POST['id'])
);
$sql = "
DELETE
FROM topic
WHERE id = {$filtered['id']}
";
$result = mysqli_query($conn, $sql);
if($result === false){
echo '저장하는 과정에서 문제가 생겼습니다. 관리자에게 문의해주세요';
error_log(mysqli_error($conn));
} else {
echo '삭제에 성공했습니다. <a href="index.php">돌아가기</a>';
}
?>
'정리 > Web dev.' 카테고리의 다른 글
[web] Cookie / Session (0) | 2023.05.14 |
---|---|
[web] 웹 기본 상식 (0) | 2023.05.07 |
[web]php 간단 정리 (0) | 2023.04.09 |
[web] javascript 총정리 (0) | 2023.04.02 |
[web] html & internet (0) | 2023.03.26 |
댓글