ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [PHP] 51. AJAX 와 MySQL ( AJAX and MySQL) - PHP 강좌, PHP5
    Web/PHP 2015. 6. 13. 14:13
    PHP - AJAX and MySQL

     




    1. AJAX Database Example

     아래 예제는 AJAX를 이용하여 웹페이지에서 데이터베이스로부터 정보를 어떻게 가져오는지에 대한 예제입니다.
     



    2. Example Explained - The MySQL Database

     데이터 베이스 테이블은 아래와 같습니다.

    idFirstNameLastNameAgeHometownJob
    1PeterGriffin41QuahogBrewery
    2LoisGriffin40NewportPiano Teacher
    3JosephSwanson39QuahogPolice Officer
    4GlennQuagmire41QuahogPilot

     

     


    3. Example Explained

     예제는 리스트 박스를 사용자가 클릭 했을 때, showUser()를 호출하게 하는 예제를 만들겠습니다.


     
    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
    <html>
    <head>
    <script>
    function showUser(str) {
        if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else { 
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","getuser.php?q="+str,true);
            xmlhttp.send();
        }
    }
    </script>
    </head>
    <body>
     
    <form>
    <select name="users" onchange="showUser(this.value)">
      <option value="">Select a person:</option>
      <option value="1">Peter Griffin</option>
      <option value="2">Lois Griffin</option>
      <option value="3">Joseph Swanson</option>
      <option value="4">Glenn Quagmire</option>
      </select>
    </form>
    <br>
    <div id="txtHint"><b>Person info will be listed here...</b></div>
     
    </body>
    </html>
    cs

     



     코드 설명:

      첫째로, 어느 사람도 선택되지 않았는지 확인합니다. 


      사람이 선택되었다면, 아래와 같은 일을 합니다:

       - XMLHttpRequest 객체를 생성

       - 서버 반응에 의해 실행되어질 함수 생성

       - 서버로 요청을 보냄

       - URL에 추가된 파라미터 q를 확인




    4. The PHP File
     자바스크립트에 의해 호출되는 서버의 페이지는 getuser.php라는 PHP 파일입니다.

       
    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
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    table {
        width: 100%;
        border-collapse: collapse;
    }
    table, td, th {
        border: 1px solid black;
        padding: 5px;
    }
    th {text-align: left;}
    </style>
    </head>
    <body>
     
    <?php
    $q = intval($_GET['q']);
     
    $servername = "localhost";
    $username = "----";
    $password = "----";
    $dbname = "mydb";
     
    // Create connection
    $con = new mysqli($servername$username$password$dbname);
     
    if (!$con) {
        die('Could not connect: ' . mysqli_error($con));
    }
     
    mysqli_select_db($con,"ajax_demo");
    $sql="SELECT * FROM user WHERE id = ".$q;
    $result = mysqli_query($con,$sql);
     
    echo "<table>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
    <th>Hometown</th>
    <th>Job</th>
    </tr>";
    while($row = mysqli_fetch_array($result)) {
        echo "<tr>";
        echo "<td>" . $row['firstname'] . "</td>";
        echo "<td>" . $row['lastname'] . "</td>";
        echo "<td>" . $row['age'] . "</td>";
        echo "<td>" . $row['hometown'] . "</td>";
        echo "<td>" . $row['job'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    mysqli_close($con);
    ?>
    </body>
    </html>
    cs
     



      




     설명:

      1. PHP는 MySQL 서버와 연결을 엽니다.

      2. 일치하는 사람을 찾습니다.

      3. HTML 테이블을 생성한 뒤, 데이터를 채우고, txtHint placeholder로 전송합니다.

     






    * 이 강좌는 'w3schools'를 참조하여 작성하였습니다.

    댓글

Designed by Tistory.