我正在使用此代码从mysql查询中获取数据。
if ($filter == "All" && $filter != "") {date_default_timezone_set('America/Denver');
$todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE events.name LIKE '%".$search."%' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."'";
}else{ $todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE events.name LIKE '%".$search."%' AND events.price = '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."' OR events.description LIKE '%".$search."%' AND events.price = '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."' OR events.user = '".$_SESSION['username']."' AND events.address LIKE '%".$search."%' AND events.price = '".$filter."' AND events.end > '".$todays123."' ";
}
这是我的javascript代码
function user_display() {
var search = document.getElementById("search").value;
if (search == "" || search == null) {
search="";
}
var filter = document.getElementById("filter").value;
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("table-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./xxx.php?action=display&search="+search+"&filter="+filter, true);
xmlhttp.send();
}
当搜索值不包含“&”时,它会正确匹配和一个“#。”当我输入&符号或哈希符号时,查询崩溃并且不显示任何内容。
有关为何这样做的任何建议?提前致谢
答案 0 :(得分:2)
您可能应该在JavaScript中使用encodeURIComponent()
。很可能你没有得到结果,因为它没有在搜索变量中传递任何东西(或者将其剪掉)。考虑搜索是否为“a& foo = c&”。您请求的网址现在为xxx.php?action=display&search=a&foo=c&filter=...
,因此您最终得到了另一个名为foo
的GET变量
var search = encodeURIComponent(document.getElementById("search").value);
filter
如果是用户将提供的内容,请执行相同操作。
答案 1 :(得分:0)
将您的代码更改为至少这样
$search = mysql_real_escape_string($search);
$filter = mysql_real_escape_string($filter);
// hopefully username in $_SESSION is clean else repeat above for that and rerun your query
if ($filter == "All" && $filter != "") {date_default_timezone_set('America/Denver');
$todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE events.name LIKE '%".$search."%' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."'";
}else{ $todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE events.name LIKE '%".$search."%' AND events.price = '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."' OR events.description LIKE '%".$search."%' AND events.price = '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."' OR events.user = '".$_SESSION['username']."' AND events.address LIKE '%".$search."%' AND events.price = '".$filter."' AND events.end > '".$todays123."' ";
}
上述更改至少可以确保可以避免SQL注入。