我正在努力尝试使用php / jquery建立一个“安全”的动态表单。我试图弄清楚如何在URL中编码查询结果,但也能够在浏览器中正确显示查询。我已经尝试在每个for循环中的数据周围包装一个urlencode但它输出编码数据并禁用填充第二个下拉列表的能力。
<!-- Populate First Dropdown -->
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=htmlentities($row["name"])?></option>
<?php endforeach ?>
</select>
<br />
<!-- Populate Second Dropdown -->
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<!-- Jquery to Populate second and Produce image -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#second-choice").change(function() {
var first = $("#first-choice").val();
var sec = $(this).val();
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
});
});
</script>
这是我使用以上jquery填充第二个下拉列表的getter.php文件:
$choice = $_GET['choice'];
$sth = $db->prepare("SELECT code FROM sets WHERE name='$choice'");
$sth->execute();
$choicecode = $sth->fetchColumn();
$stmt = $db->prepare("SELECT * FROM cards WHERE code='$choicecode'");
$stmt->execute();
$data2 = $stmt->fetchAll();
?>
<?php foreach ($data2 as $row): ?>
<option><?=$row["cardname"]?></option>
<?php endforeach ?>
基本上我想对下拉列表中的数据进行编码,因为它们包含空格和撇号。我怎样才能同时正确输出它?
答案 0 :(得分:2)
urlencode
。当您将文本放入HTML时,应使用htmlentities
。另外,使用ID列作为选项中的值。
<?php foreach ($data as $row): ?>
<option value="<?=$row["id"]?>"><?= htmlentities($row["name"]) ?></option>
<?php endforeach ?>
此外,您应该使用参数化查询来防止SQL注入,并在构造查询时避免其他问题,如果它包含特殊字符:
$stmt = $db->prepare("SELECT * FROM cards
WHERE code = (SELECT code FROM sets WHERE id = :id)");
$stmt->execute(array(':id' => $_GET['choice']));
$data2 = $stmt->fetchAll();