-
PHP PDO 사용법PHP 2021. 10. 26. 16:55
1.들어가기 앞서
- PHP진영에서 MySQL과 연동 API는 2가지가 있으며 각각 이점이 있으며 상황에 따라 적절한 것을 사용하면 된다.
- PDO는 다양한 DB와 연동할 수 있어 확장에 열려있다. 하지만 MySQLi는 이름과 같이 오직 MySQL과 연동할 수 있다.
- 둘 다 객체지향적으로 작성할 수 있으며 MySQLi는 절차적 API도 함께 제공한다.
2. PDO(PHP Data Objects)란?
- PDO는 여러 데이터베이스 작업을 위한 균일한 인터페이스를 제공하여 표준화 시킨 것이다.
3. PDO 사용법
new PDO()
- DB연결
사용법
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); 구현
$db_hostname = 'localhost';
$db_username = 'username';
$db_password = 'password';
$db_database = 'database';
try {
$dbh = new PDO("mysql:host={$db_hostname};dbname={$db_database}", $db_username, $db_password);
} catch (PDOException $e) {
throw $e;
}- 예외 처리를 통해 에러를 handling할 수 도 있다.
prepare()
- 실행할 statement을 준비하고 statement 객체를 반환
사용법
prepare(string $query) 구현
$sql = 'INSERT INTO comment (menu_id, user_id, comment_like, comment_contents, comment_created_date)
VALUES (:menu_id, :user_id, :comment_like, :comment_contents, now())';
$sth = $dbh->prepare($sql);execute()
- prepared statement를 실행
사용법
execute(an array of named values) 구현
$sth->execute([
':menu_id' => $menu_id,
':user_id' => $user_id,
':comment_like' => $comment_like,
':comment_contents' => $comment_contents
]);beginTransaction()
- transaction 시작
사용법
beginTransaction() 구현
$dbh->beginTransaction(); commit()
- transaction을 commit
사용법
commit() 구현
$dbh->commit(); rollback()
- transaction을 rollback
사용법
rollback() 구현
$dbh->rollBack(); setAttribute()
- database handle의 attribute를 설정
사용법
setAttribute(int $attribute) 구현
$dbh-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - PDO::ATTR_ERRMODE: 에러 보고.
- PDO::ERRMODE_EXCEPTION: Throw exceptions.
참조
PDO manual: https://www.php.net/manual/en/book.pdo.php
'PHP' 카테고리의 다른 글
phpMyAdmin 사용 (0) 2021.10.26 PHP, Java(Spring) 비교 (0) 2021.10.26 PHP 대체 문법(Alternative syntax) (0) 2021.08.22 PHP single quoted, double quoted (0) 2021.08.22 PHP boolean 주의할 점 (0) 2021.08.22