【发布时间】:2015-07-08 20:51:21
【问题描述】:
我有一个搜索框,用户可以在其中输入名称,它会显示"firstname", "username", "lastname", "email", "accountnumber"。到目前为止,我已经能够从数据库中获取数据,制作它的xml结构(这是学校的要求之一)。问题是如何将来自搜索框的值回显到 xml 表中,然后将结果输出到 HTML 表中?
数据库代码(文件名为 ajax-search.php):(我知道我使用的是 mysql,稍后我会修复它)
<?php
header("Content-type: text/xml");
//Create Database connection
$db = mysql_connect("127.0.0.1","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("bank",$db);
$sSearchFor = $_GET['sSearchFor'];
$sql = "SELECT * FROM customers WHERE name LIKE '%$sSearchFor%'";
$result = mysql_query($sql, $db) or die(mysql_error());
//Create SimpleXMLElement object
$xml = new SimpleXMLElement('<xml/>');
//Add each column value a node of the XML object
while($row = mysql_fetch_assoc($result)) {
$mydata = $xml->addChild('mydata');
$mydata->addChild('Id',$row['id']);
$mydata->addChild('Name',$row['name']);
$mydata->addChild('user_name',$row['user_name']);
$mydata->addChild('last_name',$row['last_name']);
$mydata->addChild('email',$row['email']);
$mydata->addChild('account_number',$row['account_number']);
}
//Create the XML file
$fp = fopen("employeeData.xml","a+");
//$fp = fopen("php://output","a+");
//Write the XML nodes
fwrite($fp,$xml->asXML()."\r\n" );
//Close the database connection
fclose($fp);
mysql_close($db);
?>
xml 代码,(文件名为 xmltable.xml):
<?xml version="1.0" encoding="utf-8"?>
<searchresults>
<name>test</name>
<username>test</username>
<lastname>test</lastname>
<email>test.test@gmail.com</email>
<accountnumber>93207802685726</accountnumber>
</searchresults>
而 ajax 的最终脚本在索引页上:
$("#btnSearch").click(function () {
var sSearchFor = $("#txtSearch").val();
var searchLink = "ajax-search.php?sSearchFor=" + sSearchFor;
$.ajax({
type: "GET",
url: "xmltable.xml",
cache: false,
dataType: "xml",
success: function (xml) {
$(xml).find('searchresults').each(function () {
$(this).find("name").each(function () {
var name = $(this).text();
alert(name);
});
});
}
});
});
感谢所有帮助,因为我现在真的很迷茫。
【问题讨论】:
-
警告:这非常不安全,因为这些参数不是properly escaped。您应该绝不将
$_GET数据直接放入查询中:它会创建一个巨大的SQL injection bug。mysql_query是一个过时的接口,不应使用,它已从 PHP 中删除。像PDO is not hard to learn 这样的现代替代品。像 PHP The Right Way 这样的指南解释了最佳实践。 -
@tadman 感谢您的提示。我知道 SQL 注入,一旦我开始工作,我会删除/改进我的答案。
-
一开始就不应该出现。 PDO 使得编写查询变得非常容易而没有这些问题。像往常一样调试这样的代码时,始终保持 JavaScript 控制台打开。这是发现脚本错误的唯一方法。密切关注网络流量,尤其是 PHP 代码的响应。
-
@tadman 会的,先生!欣赏它。