我的網站有兩個文件:search_team.php和returnPossibleTeams.php。 search_team是一個主要的HTML頁面,允許用戶輸入團隊的名稱。每當onKeyUp
被觸發時,就會調用一個JavaScript函數,它執行一個GET請求來通過AJAX返回PossibleTeams.php。 returnPossibleTeams.php需要對數據庫執行查詢,然後返回所有可能的結果。如何在僅響應Ajax請求的PHP頁面中訪問數據庫句柄?
search_team.php
<script type="text/javascript">
function showTeams(str) {
if (str.length == 0) {
document.getElementById("teamResults").innerHTML = "<br /><hr />Start typing the name of a team to search<br /><hr />";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teamResults").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "functions/returnPossibleTeams.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
<div id="main">
<br /><br />
<!-- Search for a team with it's name or ID -->
<div class="title">
Search for a Team
</div>
<div style="text-align:center;">
<br />Enter the target team's name their TFConnections team page.<br /><br />
From there, you can request an invite, view all of their rankings and members, and even
<i>challenge</i> them (if you're in a team of your own).<br />You can also view information
about possible upcoming events and other details they've set up!<br /><br />
<input placeholder="Team Name" onkeyup="showTeams(this.value);" type="text" name="searchterms">
<div id="teamResults">
<hr />Start typing the name of a team to search<br /><hr />
</div>
<br />
</div>
</div>
應當指出的是,該網頁中包含的header.php,它創建了一個PDO MySQL數據庫的連接,並存儲在$db
處理。
returnPossibleTeams.php
<?php
if (isset($_GET['q'])) {
try {
$statement = $db->prepare("SELECT * FROM `teams` WHERE `Team Name` LIKE %:teamname%");
$result = $statement->execute(array('teamname' => $_GET['q']));
} catch (Exception $e) {
echo "An error has occured.";
}
echo $statement->fetch(PDO::FETCH_ASSOC)['Team Name'];
}
?>
我有這裏的問題是,returnPossibleTeams.php不能訪問數據庫$db
手柄,因爲它已經建立了一個文件包括在開始search_team.php。解決這個缺失追索權問題的最簡單方法是在returnPossibleTeams.php開始時創建一個新的數據庫連接,但這樣效率極低,因爲每次用戶按下一個鍵時都會創建一個新的數據庫連接!解決這個問題的最好方法是什麼?
'$ db'永遠不會被設置。 – carefulnow1
你是什麼意思,它永遠不會被設置? – Donniep
我不知道我怎麼可以更清楚......'$ db'永遠不會被設置,因爲它是一個單獨的文件,創建數據庫句柄的位置。 – carefulnow1