我第一次尝试了一些ajax。我正在尝试编写一个实时搜索,其中每个字符都会进入MySQL数据库的搜索。
到目前为止,这是我的代码:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script type="text/javascript">
function getStates(value){
$.post(
"getstates.php",
{partialState:value},
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
getStates.php
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$partialState = $_POST['partialState'];
$query = $dbh->prepare("SELECT state_name FROM tbl_state WHERE state_name LIKE '%$partialSate%'");
$query->execute();
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
使用正确的表名等正确构建mySQL数据库。
为什么不从数据库返回结果状态?
答案 0 :(得分:0)
问题是您在查询中输了一个拼写错误:
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialSate%'");
^^^^Missing t
应该是
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialState%'");
但你也应该正确使用准备好的查询: 固定代码:
<?php
if(isset($_POST['partialState'])){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE :like");
$query->execute(array(':like'=>'%'.$_POST['partialState'].'%'));
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
die();
}
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("index.php", { "partialState":value },
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>