【发布时间】:2013-12-18 20:32:11
【问题描述】:
我正在使用this answer 中的技术使用 MySQL 条目填充下拉列表。这很好 - 当我选择一个事件时,会生成一个新的下拉列表,其中包含该事件的运行日期。
但是,我还需要从数据库中检索事件的成本,并将其分配为表单输入的值。最简单的方法是将其分配给事件下拉列表的 value 属性,但这已用于生成第二个下拉列表。
所以,我想我可以在事件下拉列表的change 事件中使用另一个 Ajax 调用来再次查询数据库并获取成本,然后将其作为 JSON 编码变量传回。这是我的 Ajax 调用:
$('#event_menu').on('change', function() {
// get selected value and build data string for AJAX
var event_selected = "event_selected="+$(this).val();
// send the selected data to a PHP page to build the populated menu
$.ajax({
url : 'populate_menu.php',
type: 'POST',
data : event_selected,
dataType : 'html',
success : function(data) {
$('#instancemenu').html(data);
}, error : function() {
alert("Something went wrong!");
}
});
$.ajax({
url : 'get_eventprice.php',
type: 'POST',
date: event_selected,
dataType : 'json',
success : function(data){
$('#totalcost').val(data);
}, error : function(){
alert("Something went wrong with the price setter!")
}
});
});
这是get_eventprice.php中的代码:
$event_selected = isset($_POST['event_selected']) ? $_POST['event_selected'] : null;
$q="SELECT event_cost FROM events WHERE event_id=$event_selected";
$r=mysqli_query($dbc,$q);
$row=mysqli_fetch_field($r, MYSQLI_ASSOC);
echo json_encode($row['course_cost']);
但是,这会触发 Ajax 调用中的错误子句。我也试过mysqli_fetch_array,但没有运气。我做错了什么?
【问题讨论】:
-
您的代码容易受到 SQL 注入的影响,并且将来会成为问题 - 无论是有意还是无意。 永远不要相信用户变量。查看bobby-tables.com
-
使用
mysqli时,您应该使用参数化查询和bind_param将用户数据添加到您的查询中。 避免使用字符串插值来完成此操作。 -
顺便说一句,如果 course_cost 只是一个数值,你可以跳过
json_encode。 -
@nl-x 试过了,还是不行
-
@h2ooooooo 使用准备好的语句与使用
mysqli_real_escape_string过滤 POST 变量相比如何?
标签: php jquery mysql ajax json