최신 웹 개발 튜토리얼
 

PHP - AJAX와 MySQL


AJAX는 데이터베이스와의 쌍방향 커뮤니케이션에 사용할 수 있습니다.


AJAX 데이터베이스 예

다음의 예는 웹 페이지가 AJAX와 데이터베이스에서 정보를 가져올 수있는 방법을 보여줍니다 :


Person info will be listed here...

예 설명 - MySQL 데이터베이스를

우리는 위의 예에서 사용하는 데이터베이스 테이블은 다음과 같다 :

신분증 이름 나이 고향
1 베드로 그리핀 (41) Quahog 양조장
로이스 그리핀 (40) 뉴 포트 피아노 교사
조셉 스완슨 (39) Quahog 경찰관
4 글렌 소택지 (41) Quahog 조종사


예 설명

사용자가, 전술의 드롭 다운리스트라는 함수를 사람을 선택하는 전술 한 실시 예에서, " showUser() " 이 실행된다.

이 기능은 onchange를 이벤트에 의해 트리거됩니다.

여기에 HTML 코드는 다음과 같습니다

<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>
»실행 예

코드 설명 :

어떤 사람이 선택되어 있지 않은 경우 먼저 확인 (str == "") . 어떤 사람도 선택하지 않으면 txtHint 자리의 내용을 지우고 기능을 종료합니다.

사람을 선택하면, 다음을 수행하십시오

  • XMLHttpRequest를 객체를 생성
  • 서버 응답이 준비되었을 때 실행되는 함수를 만듭니다
  • 서버에 파일로 요청을 보내기
  • 매개 변수 것을 알 (q) (드롭 다운 목록의 내용)를 URL에 추가

PHP 파일

위의 자바 스크립트에 의해 호출 된 서버의 페이지라는 PHP 파일입니다 "getuser.php" .

의 소스 코드 "getuser.php" MySQL 데이터베이스에 대해 쿼리를 실행하고 HTML 테이블에 결과를 반환합니다 :

<!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']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
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>

설명 : 쿼리가 PHP 파일에 자바 스크립트에서 전송 될 때, 다음과 같은 상황이 발생 :

  1. PHP는 MySQL 서버에 대한 연결을 엽니 다
  2. 올바른 사람이 발견
  3. HTML 테이블이 생성 된 데이터로 가득하고, 다시 전송됩니다 "txtHint" 자리