<分区>
我正在尝试使用 jQuery、Ajax 和 PHP 为 MySQL 表创建一个搜索引擎。我的外部服务器上有一个数据库,以便从中获取数据。这是 MySQL 数据库表的图片。
我有这两个搜索引擎脚本:
index.html
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input id="searchdb"/>
<div id="resultdb"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#searchdb').change(function() {
$.ajax({
type: 'GET',
url: 'getdb.php',
data: 'ip=' + $('#searchdb').val(),
success: function(msg) {
$('#resultdb').html(msg);
}
});
});
});
</script>
</body>
</html>
getdb.php
<?php
if ($_GET['insert']) :
$insert = preg_replace('#[^0-9]#', '', $_GET['insert']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc()
echo $row["name"];
}
endif;
?>
我想要的是键入 ID,按回车键并取回名称或“0 个结果”。我写的代码似乎有问题。请你帮助我好吗?提前致谢。