관리 메뉴

Today is Present.

[PHP] ajax와 mysql 연동하기 2 본문

프로그래밍, 코딩

[PHP] ajax와 mysql 연동하기 2

MorningPhys 2021. 2. 9. 09:28
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','user_id','user_pwd','test_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT * FROM persons WHERE user_name = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>username</th>
<th>Age</th>
<th>Home</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['home'] . "</td>";
echo "<td>" . $row['job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
// 출처: https://makand.tistory.com/entry/PHP-AJAX-데이터베이스-연동 [Park'S의 IT 이야기]
view raw ajax.php hosted with ❤ by GitHub
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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","ajax.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="park">park</option>
<option value="kim">kim</option>
<option value="song">song</option>
<option value="lee">lee</option>
</select>
</form>
<br>
<div id="txtHint"><b>사람들의 정보를 이곳에 보여줌.</b></div>
</body>
</html>
// 출처: https://makand.tistory.com/entry/PHP-AJAX-데이터베이스-연동 [Park'S의 IT 이야기]
view raw index.php hosted with ❤ by GitHub

 

728x90
반응형