2017-05-06 31 views
0

我的網站有兩個文件: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開始時創建一個新的數據庫連接,但這樣效率極低,因爲每次用戶按下一個鍵時都會創建一個新的數據庫連接!解決這個問題的最好方法是什麼?

回答

-1

你可以把它放在一個條件。

if(!isset($db)) { 
    //Here you have two choices either just connect to the database or require the fb connection file. Either way you need to connect to the database. 
} 

這種方式,如果它已經設置它不會創建一個新的連接。

編輯:我的確認爲PHP會在每次調用時建立一個新的連接,因爲它是PHP的工作原理。一旦腳本完成運行並返回數據,它將結束關閉數據庫連接。

+0

'$ db'永遠不會被設置。 – carefulnow1

+0

你是什麼意思,它永遠不會被設置? – Donniep

+0

我不知道我怎麼可以更清楚......'$ db'永遠不會被設置,因爲它是一個單獨的文件,創建數據庫句柄的位置。 – carefulnow1