사자자리
[PHP & MySQL] PHP와 MySQL의 연동 본문
PHP와 MySQL의 연동 원리
1. 웹브라우저에 index.php 입력
2. 웹브라우저가 index.php 파일을 가지고 있는 웹서버에 접속
3. 웹서버가 PHP에게 index.php 파일의 처리를 위임
4. PHP가 index.php 파일의 PHP 코드를 PHP 문법에 따라 해석하고 동작
5. index.php 파일의 PHP 코드 중에 MySQL 관련 함수가 있으면, PHP가 MySQL에게 SQL문을 전달
6. MySQL이 SQL문을 따라 동작하고 결과를 PHP에게 전달
7. PHP가 최종적으로 순수한 HTML 코드를 생성
8. 웹서버가 HTML 코드를 웹브라우저에게 전송
*이 맥락에서, PHP는 웹서버와 MySQL 사이의 중개자 역할을 한다. 이를 미들웨어(Middleware)라고도 한다.
MySQL 클라이언트로서의 PHP
- PHP에서 제공하는 함수를 이용하면, PHP가 MySQL 서버에 SQL문을 전송하고 다시 받는다.
- 즉, 앞으로의 PHP는 MySQL 서버에 대해서 클라이언트이다.
MySQL API
- PHP를 이용해서 MySQL을 사용하는 Application Programming Interface
- mysqli 사용: 수업에서는 객체 지향 대신 함수 사용
수업 준비
웹
<!--htdocs\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, 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>
데이터베이스
C:\Users\renne>cd C:\Bitnami\wampstack-8.1.7-1\mariadb\bin
C:\Bitnami\wampstack-8.1.7-1\mariadb\bin>mysql -uroot -p
Enter password: **********
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.4.25-MariaDB mariadb.org binary distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| opentutorials |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.033 sec)
MariaDB [(none)]> USE opentutorials;
Database changed
MariaDB [opentutorials]> 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;
Query OK, 0 rows affected (0.039 sec)
MariaDB [opentutorials]> DESC topic;
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(45) | NO | | NULL | |
| description | text | YES | | NULL | |
| created | datetime | NO | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
4 rows in set (0.017 sec)
PHP와 MySQL 연동하기
<!--htdocs\insert.php-->
<?php
$conn = mysqli_connect("localhost", "root", "******", "opentutorials"); //데이터베이스 서버에 접속
//mysqli_connect("DB Server 주소", "user", "password", "사용할 DB 이름");
$sql = "INSERT INTO topic(title, description, created) VALUE('MySQL', 'MySQL is ...', NOW())";
$result = mysqli_query($conn, $sql);
//mysqli_query($link, "SQL문");
?>
//웹페이지 http://127.0.0.1/insert.php를 load했을 때, mysqli_query 함수가 실행되면서 SQL문이 실행됐다.
MariaDB [opentutorials]> select * from topic;
+----+-------+--------------+---------------------+
| id | title | description | created |
+----+-------+--------------+---------------------+
| 1 | MySQL | MySQL is ... | 2022-08-01 22:33:48 |
+----+-------+--------------+---------------------+
1 row in set (0.000 sec)
Error의 이유 알아보기
- PHP는 에러의 이유를 알려주지 않으므로, SQL문을 cmd에 입력하면 에러의 이유를 알아볼 수 있다.
- mysqli_error 함수 사용하기
<!--htdocs\insert.php-->
<?php
$conn = mysqli_connect("localhost", "root", "021103", "opentutorials");
$sql = "INSERT INTO topic(title, description, created) VALUE('MySQL', 'MySQL is ...', NOW())";
$result = mysqli_query($conn, $sql);
if ($result === false){ //mysqli_query는 failure하면 false를 return한다.
echo mysqli_error($conn); //error의 이유를 알려주는 함수
//error의 이유가 echo되면 위험하므로, 개발 중에만 쓰는 방법이다.
}
?>
'웹기초 > 생활코딩 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] 웹페이지에 입력한 데이터를 테이블에 추가하기 (0) | 2022.08.03 |
Comments