使用PHP AJAX和XML进行实时搜索

我在网上搜索过,我在w3schools上找到了这个链接,告诉你如何用Php,Ajax和XML进行实时搜索( 链接 )。 我可以理解他们在他们的代码上做了什么,如下所示……

search.php文件

    function showResult(str) { if (str.length==0) { document.getElementById("livesearch").innerHTML=""; document.getElementById("livesearch").style.border="0px"; 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("livesearch").innerHTML=xmlhttp.responseText; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","livesearch.php?q="+str,true); xmlhttp.send(); }    

和livesearch.php文件

 load("links.xml"); $x=$xmlDoc->getElementsByTagName('link'); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of q>0 if (strlen($q)>0) { $hint=""; for($i=0; $ilength); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1) { //find a link matching the search text if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint=="") { $hint="item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . ""; } else { $hint=$hint . "
item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . ""; } } } } } // Set output to "no suggestion" if no hint was found // or to the correct values if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?>

但他们接下来要做的是拥有一个包含他们想要搜索的所有数据的xml页面( 链接 ),但在我的情况下,我想搜索我的数据库表,而我正在使用SQL。 我试着做一些编码,但我找不到如何从查询中获取数据。

links.xml文件

    Also display here the name of the user members2.php?view=?????   

无论我在哪里???? 意味着我不知道在那里写什么。 也许xml的代码需要更多的代码。

你能帮我修复我的xml并让它显示我数据库的结果

您需要编辑的文件是livesearch.php文件。 Links.xml由livesearch.php读取为数据源,在您的情况下将是数据库。 修改后的livesearch.php看起来如下所示:

 prepare("SELECT * FROM patient WHERE fname LIKE :q OR lname LIKE :q"); $stmt->bindValue(':q', '%'.$_GET['q'].'%'); $stmt->execute(); while ( $row = $stmt->fetchObject() ) { echo '' . $row->fname . ' ' . $row->lname . '
'; } ?>

这将产生与w3schools提供的livesearch.php示例类似的输出。