duanhao8540 2012-11-19 14:44
浏览 41
已采纳

如何使用AJAX和PHP将数据添加到sql db中

I have 2 input fields "User" and "Comment" and I want the user input to be saved asynchronously using AJAX, so no refreshing. So far I've gotten it to add a new row to the DB, but for some reason it is empty. I believe the reason is I am not appending the values correctly.

HTML(JS is in-between head tags):

<p>User: <input type="text" id="userName" /></p>
<p>Comment : <input type="text" id="comment" /></p>
<input type="button" value="Submit" onclick="callServer();" />

JS:

function callServer(){
  var usr = document.getElementById("user").value;
  var cmnt = document.getElementById("comment").value;
  var ajaxRequest = XMLHttpRequest();

  ajaxRequest.open("POST", "insert.php", true);
  ajaxRequest.send(null);
}

PHP:

<?php
// Setting variables for the elements
$user = $_POST['user'];
$comment = $_POST['comment'];

// Establishing connection and selecting db    
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db('local',$con);

// Doing the query for the insert
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comment')");

mysql_query($query, $con);
mysql_close($con);
?>
  • 写回答

2条回答 默认 最新

  • doucuoyan0426 2012-11-19 14:53
    关注

    Your input ID is userName but you are targeting user.

    Change to:

    var usr = document.getElementById("userName").value;
    

    You are also sending null with the ajax request, you should be sending your data:

    var params = "user=" + encodeURIComponent(usr) + "&comments=" + encodeURIComponent(cmnt);
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    ajaxRequest.send(params);
    

    Also, you should include the content-type header - as above.

    Finally, the mysql_* library is deprecated, you should use a modern API such as PDO or MySQLi for any new development. Because you're using this library you need to escape post data for SQL Injection:

    $user = mysql_real_escape_string($_POST['user']);
    $comment = mysql_real_escape_string($_POST['comment']);
    

    If you use a modern API, you can do parameterised queries which don't require you to manually escape anything.

    Also just noticed, remove this line:

    mysql_query($query, $con);
    

    You have already executed the query on the line before that. This line is useless and will fail, it is trying to execute another query using the result resource of the first query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 想写一个文件管理器,加载全部子文件夹后,要一级一级返回
  • ¥15 华为超融合部署环境下RedHat虚拟机分区扩容问题
  • ¥15 哪位能做百度地图导航触点播报?
  • ¥15 请问GPT语言模型怎么训练?
  • ¥15 已知平面坐标系(非直角坐标系)内三个点的坐标,反求两坐标轴的夹角
  • ¥15 webots有问题,无响应
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?