【问题标题】:Can't insert record into database using jQuery无法使用jQuery将记录插入数据库
【发布时间】:2013-08-25 23:42:19
【问题描述】:

我正在尝试使用 jQuery Ajax 和 PHP 将记录插入 MySQL 数据库。我的问题是它没有在表中插入任何行。我试过这段代码:

对于 html :

 `<script>
$(function(){
    //insert record
    $('#insert').click(function(){
        var jcomments_manager = $('#fcomments_manager').val();


        //syntax - $.post('filename', {data}, function(response){});
        $.post('data.php',{action: "insert", name:jcomments_manager},function(res){
            $('#result').html(res);
        });     
    });

    //show records
    $('#show').click(function(){
        $.post('data.php',{action: "show"},function(res){
            $('#result').html(res);
        });     
    });
});
</script>
Add a comment: <input type="text" id="fcomments_manager" />

            <button id="insert">Insert</button>

`

对于 php:

`if($_POST['action'] == 'insert'){

    $comments_manager  = mysql_real_escape_string($_POST['comments_manager']);

    $c_id = $_GET['c_id'];

    $sql   = "INSERT INTO candidate (comments_manager) 
                VALUES ('$comments_manager')
               WHERE c_id = '$c_id'
               ";
    $query = mysql_query($sql);
    if($query){
        echo "Record Inserted.";
    }else {
        echo "Something Wrong!";
    }
}

`

【问题讨论】:

标签: jquery mysql sql


【解决方案1】:

您的参数名称不匹配

    //in server the manager parameter is read using name `comments_manager`, here you were passing it as name
    $.post('data.php',{action: "insert", comments_manager:jcomments_manager},function(res){
        $('#result').html(res);
    });

【讨论】:

  • 谢谢。但我也有同样的问题。
  • @user2703341 使用您的浏览器开发者工具网络选项卡检查 ajax 请求以查看正在发送的数据
  • 我是编程新手,你能解释一下你的意思吗?
【解决方案2】:

$comments_manager = mysql_real_escape_string($_POST['comments_manager']);

不应该这样吗:

$comments_manager = mysql_real_escape_string($_POST['name']);

【讨论】:

  • 达尼特。 Arun 快了 9 秒。
  • 好的,我解决了这个问题,但我有同样的问题
  • 正如 Ken Cheung 所说,您应该将 $_GET["c_id"] 传递给 data.php,因此将 $.post url 设为“data.php”。 $_GET["c_id"]。如果我是你,我会确保 GET 值。
  • 你能发一下具体需要写什么吗?
  • $.post('data.php?c_id='. $_GET["c_id"],{action: "insert", name:jcomments_manager}
猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 2021-03-11
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多