尝试使用表单向MYSQL添加多个记录

时间:2015-03-03 21:47:45

标签: php jquery mysql forms pdo

我有一个表单,允许用户添加新的课程标题,并为他们提供添加更多记录的选项,使其更方便,而不是单独提交每个。

我尝试使用我在网上的一些示例中看到的语法,它可以动态添加额外的行,但这会影响连接到mysql数据库时的表单提交。

它会添加第一条记录而不是第二条记录,我不确定我是否使用PDO正确执行它。

如果有人能够提供一些有关我如何实现这一点以及为什么我的代码失败的见解,我会非常感激。

php文件:

<?php

include "db_conx.php";

try
{
    $db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);

    $db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`) VALUES (:course_title)");

    $course_title = $_POST['course_title'];
        //$course_code = $_POST['course_code'];

    $sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
        //$sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);


    /*** execute the prepared statement ***/

    $courses = array();
    if ($sql->execute()) {
            $courses[] = $sql;
        }
    }

    /*** success message ***/


    $message = "<p class='text-success'> Record Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
} 
catch(Exception $e)
{
    $message = 'Message: ' .$e->getMessage();
}


die($message);
?>

AJAX,点击时会添加更多行,并在提交时提交表单。点击:

function addCall() {
  var data = $('#addForm').serialize();
  $.post('ManageCourses_AddSubmit.php', data, function(response){

    $("#addForm").html(response);
    //'soft'reload parent page, after a delay to show message
    setTimeout(function(){
      $('#addModal').modal('hide')
      location.reload();
    },3500);

  }).fail(function(jqXHR, textStatus) {
    alert( "Request failed: " + textStatus );
  });
}

jQuery(function($){
    var i = 1;
    var $button = $('#add_row'),
        $row = $('.addForm').clone();

    $button.click(function(){
        $row.clone().insertBefore( $button );
    });
});

从中发送数据的表单:

                <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title">Add New Record: </h4>
                            </div>
                            <div class="modal-body">
                                <form id="addForm" class="addForm">
                                    <div class="form-group">
                                        <label for="course_code" class="pull-left" class="control-label">Course Code:</label>
                                        <input type="text" class="form-control" id="course_code_id" name="code[]" readonly value ="NULL">
                                    </div>
                                    <div class="form-group">
                                        <label for="course_name" class="pull-left" class="control-label">Course Title:</label>
                                        <input type="text" class="form-control" placeholder="Enter Course Title" id="course_title_id" name="course_title">
                                    </div>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <div class="btn-toolbar">
                                    <button type="button" class="btn btn-primary" id="add_row" name="add_row">Add New Record <span class="glyphicon glyphicon-plus"></button>
                                    <button type="button" class="btn btn-danger" id="del_row" name="del_row">Delete Row <span class="glyphicon glyphicon-trash"></button>
                                    <button type="button" class="btn btn-default" class="pull-right" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-success" class="pull-right" onclick="addCall();">Submit <span class="glyphicon glyphicon-saved"></button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
谢谢你! :)

1 个答案:

答案 0 :(得分:0)

您的问题来自于定位以下行中的元素ID:

var data = $('#addForm').serialize();

首先,您应该始终将id属性视为仅存在于DOM的一个位置。有关更多信息,请参阅:

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute

要解决您的问题,您需要传递每个元素的数据,并在后端以不同方式处理数据。在JavaScript中,更改以下行:

var data = $('#addForm').serialize();

为:

var data = {};
var index = 0;
// use the class of the form elements instead
$('.addForm').each(function(){
  // take each form value an store it within the data variable
  data['course_code'][index] = $(this).find('input[name=course_code]').val();
  data['course_title'][index] = $(this).find('input[name=course_title]').val();
  index++;
});

现在,您需要更新后端以接受新的值数组...

<?php

include "db_conx.php";

try
{
    $db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);

    $db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $courses = array();
    // check if we have valid post data
    if(isset($_POST['course_code']) && isset($_POST['course_title']))
    {
      foreach($_POST['course_code'] as $index=>$course_code)
      {
        // check if we have a matching title (needed for the title insert)
        $course_title = '';
        if(isset($_POST['course_title'][$index]))
          $course_title = $_POST['course_title'][$index];
        else
          continue; // no title found, skip to the next index

        // at this point, use $course_title and $course_code in your query
        $sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`, `course_code`) VALUES (:course_title, :course_code)");

        $sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
        $sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);

        /*** execute the prepared statement ***/
        if ($sql->execute()) {
          $courses[] = $sql;
        }
      }
    }

    /*** success message ***/


    $message = "<p class='text-success'> Records Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
} 
catch(Exception $e)
{
    $message = 'Message: ' .$e->getMessage();
}


die($message);
?>