希望只是一个快速的答案,我可以看到问题的各种答案,但发现很难在我的代码中实现。 正如标题所示,希望在使用 ajax 和 javascript 将数据发布到 MySQL 时允许使用撇号。刚才提交数据的时候,不行。
希望有人能够最终确定代码以使其工作。
HTML
<!-- Modal - Add New Record/Info -->
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add some useful information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="add_info">Add Info</label>
<input type="text" id="info" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="addRecord()">Add Record</button>
</div>
</div>
</div>
</div>
<!-- // Modal -->
Javascript
// Add Record
function addRecord() {
// get values
var info = $("#info").val();
// Add record
$.post("ajax/addRecord.php", {
info: info
}, function (data, status) {
// close the popup
$("#add_new_record_modal").modal("hide");
// read records again
readRecords();
// clear fields from the popup
$("#info").val("");
});
}
Ajax - addRecord.php
<?php
if(isset($_POST['info']))
{
// include Database connection file
include("db_connection.php");
// get values
$info = $_POST['info'];
$query = "INSERT INTO useful_info(info) VALUES('$info')";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
echo "1 Record Added!";
}
?>
通过阅读网站上的其他问题,我可以使用 get_magic_quotes_gpc
或者通过创建 JSON 对象并使用 JSON.stringify
。只是想知道如何最好地实现这一目标。
如有任何帮助,我们将不胜感激。
最佳答案
根据 @JimL 的 comment ,您应该切换到 mysqli 或 PDO 并使用参数化查询,因为 mysql 扩展名是 deprecated .
例如(PDO):
$stmt = $pdo->prepare("INSERT INTO useful_info(info) VALUES(?)");
if (!$stmt->execute([$info])) {
exit(implode(" :: ", $stmt->errorInfo()));
}
关于javascript - 使用 Ajax 和 Javascript 将数据发布到 MySQL 时允许使用撇号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654451/