LinkedNestBlog

PHP 문법 : PDO

by 이진원Dev
PHP 문법 : PDO


Ref.] https://opentutorials.org/module/6/5155


  • 설정
    • 대상 : php.ini
    • 위치 : 
      /Applications/mampstack-5.6.20-0/php/etc
    • 수정할 내용 :
      // 아래 내용 앞에 붙어있는 ';' 주석 제거
      extension=php_pdo_mysql.dll

  • 기본적인 CRUD 
    • list
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        69
        70
        71
        72
        73
        74
        75
        76
        77
        78
        79
        80
        81
        82
        83
        84
        85
        <?php
            $db_con = new PDO('mysql:host=127.0.0.1;dbname=php_exercise', 'root', '');
            if(!empty($_GET['id'])){
                $stmt = $db_con -> prepare("select * from article where id = :id");
                $stmt -> bindParam(':id', $id, PDO::PARAM_INT);
                $id = $_GET['id'];
                $stmt -> execute();
                $article = $stmt -> fetch();
            }
            $stmt = $db_con -> prepare('select * from article');
            $stmt -> execute();
            $list = $stmt -> fetchAll();        
            
        ?>
         
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8" />
                <style type="text/css">
                    body {
                        font-size: 0.8em;
                        font-family: dotum;
                        line-height: 1.6em;
                    }
                    header {
                        border-bottom: 1px solid #ccc;
                        padding: 20px 0;
                    }
                    nav {
                        float: left;
                        margin-right: 20px;
                        min-height: 1000px;
                        min-width:150px;
                        border-right: 1px solid #ccc;
                    }
                    nav ul {
                        list-style: none;
                        padding-left: 0;
                        padding-right: 20px;
                    }
                    article {
                        float: left;
                    }
                    .description{
                        width:500px;
                    }
                </style>
            </head>
           
            <body id="body">
                <div>
                    <nav>
                        <ul>
                            <?php
                            foreach($list as $row) {
                                echo "<li><a href=\"?id={$row['id']}\">".htmlspecialchars($row['title'])."</a></li>";                        }
                            ?>
                        </ul>
                        <ul>
                            <li><a href="input.php">추가</a></li>
                        </ul>
                    </nav>
                    <article>
                        <?php
                        if(!empty($article)){
                        ?>
                        <h2><?=htmlspecialchars($article['title'])?></h2>
                        <div class="description">
                            <?=htmlspecialchars($article['content'])?>
                        </div>
                        <div>
                            <a href="modify.php?id=<?=$article['id']?>">수정</a>
                            <form method="POST" action="write.php?mode=delete">
                                <input type="hidden" name="id" value="<?=$article['id']?>" />
                                <input type="submit" value="삭제" />
                            </form>
                        </div>
                        <?php
                        }
                        ?>
                    </article>
                </div>
            </body>
        </html>    
        cs
    • write 
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8"/>
            </head>   
            <body>
                <form action="./execute.php?mode=insert" method="POST">
                    <p>제목 : <input type="text" name="title"></p>
                    <p>본문 : <textarea name="content" id="content" cols="30" rows="10"></textarea></p>
                    <p><input type="submit" /></p>            
                </form>
            </body>
        </html>
         
        cs
    • modify
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        <?php
        $db_con = new PDO('mysql:host=127.0.0.1;dbname=php_exercise', 'root', '');
        $stmt = $db_con -> prepare('SELECT * FROM article WHERE id = :id');
        $stmt -> bindParam(':id', $id, PDO::PARAM_INT);
        $id = $_GET['id'];
        $stmt -> execute();
        $article = $stmt -> fetch();
        ?>
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8"/>
            </head>   
            <body>
                <form action="./execute.php?mode=modify" method="POST">
                    <input type="hidden" name="id" value="<?=$article['id']?>" />
                    <p>제목 : <input type="text" name="title" value="<?=htmlspecialchars($article['title'])?>"></p>
                    <p>본문 : <textarea name="content" id="" cols="30" rows="10"><?=htmlspecialchars($article['content'])?></textarea></p>
                    <p><input type="submit" /></p>
                </form>
            </body>
        </html>
        cs
    • execute
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        <?php
        $dbcon = new PDO('mysql:host=127.0.0.1;dbname=php_exercise', 'root', '', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        switch($_GET['mode']){
            case 'insert' : 
                $stmt = $dbcon->prepare("INSERT INTO article (title, content, create_date) VALUES (:title, :content, now())");
                // 파라미터 바인딩
                $stmt -> bindParam(':title', $title);
                $stmt -> bindParam(':content', $content);
         
                // 파라미터 설정
                $title = $_POST['title'];
                $content = $_POST['content'];
         
                // sql 실행
                $stmt -> execute();
         
                header("Location: list.php");
                break;
            case 'delete' :
                $stmt = $dbcon->prepare("DELETE FROM article WHER id = :id)");
                // 파라미터 바인딩
                $stmt -> bindParam(':id', $id);
         
                // 파라미터 설정
                $id = $_POST['id'];
         
                // sql 실행
                $stmt -> execute();
         
                header("Location: list.php");
                break;    
            case 'modify' : 
                $stmt = $dbcon->prepare("UPDATE article SET title = :title, content = :content WHERE id = :id");
                // 파라미터 바인딩
                $stmt -> bindParam(':title', $title);
                $stmt -> bindParam(':content', $content);
                $stmt -> bindParam(':id', $id);
                // 파라미터 설정
                $title = $_POST['title'];
                $content = $_POST['content'];
                $id = $_POST['id'];
                
                // sql 실행
                $stmt -> execute();
         
                header("Location: list.php?id={$_POST['id']}");
                break;        
        }
        ?>
        cs


  • Error
    Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] 
    No such file or directory' in /Applications/mampstack-5.6.20-0/apache2/htdocs/pdo/write.php:2
    Stack trace: #0 /Applications/mampstack-5.6.20-0/apache2/htdocs/pdo/write.php(2):
    PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 {main}
    thrown in /Applications/mampstack-5.6.20-0/apache2/htdocs/pdo/write.php on line 2
  • 해결
    PDO('mysql:host=localhost 에서 localhost를 127.0.0.1로 수정.
PHP 문법 : PDO · LinkedNest Blog