PHP - AJAX 및 MySQL
AJAX는 데이터베이스와의 대화식 통신에 사용할 수 있습니다.
AJAX 데이터베이스 예
다음 예는 웹 페이지가 AJAX를 사용하여 데이터베이스에서 정보를 가져오는 방법을 보여줍니다.
예시
Person info will be listed here...
예제 설명 - MySQL 데이터베이스
위의 예에서 사용하는 데이터베이스 테이블은 다음과 같습니다.
id | FirstName | LastName | Age | Hometown | Job |
---|---|---|---|---|---|
1 | Peter | Griffin | 41 | Quahog | Brewery |
2 | Lois | Griffin | 40 | Newport | Piano Teacher |
3 | Joseph | Swanson | 39 | Quahog | Police Officer |
4 | Glenn | Quagmire | 41 | Quahog | Pilot |
예시 설명
위의 예에서 사용자가 위의 드롭다운 목록에서 사람을 선택하면 "showUser()"라는 함수가 실행됩니다.
이 함수는 onchange 이벤트에 의해 트리거됩니다.
HTML 코드는 다음과 같습니다.
예시
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.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 객체 생성
- 서버 응답이 준비되었을 때 실행할 함수 생성
- 서버의 파일로 요청 보내기
- URL에 매개변수(q)가 추가됩니다(드롭다운 목록의 내용 포함).
PHP 파일
위의 자바스크립트가 호출하는 서버의 페이지는 "getuser.php"라는 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>
설명: 쿼리가 JavaScript에서 PHP 파일로 전송되면 다음이 발생합니다.
- PHP는 MySQL 서버에 대한 연결을 엽니다.
- 올바른 사람을 찾았습니다.
- HTML 테이블이 생성되고 데이터로 채워지며 "txtHint" 자리 표시자로 다시 전송됩니다.