我使用jquery代码将表单数据传递给php,然后php代码将数据保存到mysql数据库。如果标题为"how to save & to mysql database using php"
,则标题将作为"how to save"
存储在数据库中。我该如何解决这个问题?
这是我的JS代码
var dataString = 'title='+ title + '&url=' + url + '&description=' + description + '&published=' + published+ '&catid=' + catid;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$(".button").hide();
$('#messages').html("<div id='message'></div>");
$('#message').html("<h2>weblink Form Submitted!</h2>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
和php代码
<?php
$con = mysql_connect("localhost","db","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dalanrep_dalanreportcom", $con);
$title = mb_convert_encoding(trim($_POST['title']),'HTML-ENTITIES', 'UTF-8');
$url = mb_convert_encoding(trim($_POST['url']),'HTML-ENTITIES', 'UTF-8');
$description = mb_convert_encoding(trim($_POST['description']),'HTML-ENTITIES', 'UTF-8');
$published = mb_convert_encoding(trim($_POST['published']),'HTML-ENTITIES', 'UTF-8');
$catid = mb_convert_encoding(trim($_POST['catid']),'HTML-ENTITIES', 'UTF-8');
$title =mysql_escape_string($title );
$url = mysql_escape_string($url );
$description = mysql_escape_string($description );
$sql="INSERT INTO table (title, url, description,catid)
VALUES ('$title','$url','$description','$catid')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
答案 0 :(得分:7)
&
是网址中的特殊字符。它是多个参数的分隔符。您需要 通过encodeURIComponent()
var dataString = 'title' + encodeURIComponent(title) + '&url=' + encodeURIComponent(url) ... ;
或将参数作为JS对象{}
提供,以便jQuery自己处理它。
var data = {
"title": title,
"url": url,
...
};
答案 1 :(得分:0)
如果是&符号,则需要对&符号进行编码,而不是段分隔符。
<?php
$var = "some title with an & in it";
$title = htmlentities($var);
...
?>