8 Replies - 1875 Views - Last Post: 06 March 2015 - 02:52 PM Rate Topic: -----

#1 sonia610   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 02-March 15

Attempting to add multiple records to MYSQL using form

Posted 03 March 2015 - 03:19 PM

I have a form which allows a user to add a new course title and gives them the option to add more record making it more convenient instead of submitting each one separately.

I've attempted to use syntax which I've seen in a number of examples online and it works in adding extra rows dynamically however this affects the form submission when it connects to the mysql database.

It will add the first record however not the second and I'm not sure if I'm executing it correctly using PDO.

if anyone could provide some insight as to how i can achieve this and why my code is failing i would be much appreciative.

the php file:

<?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);
?>



the AJAX which adds more rows when clicked and submits the form when 'submit' is clicked:

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 );
    });
});



the form where the data is sent from:

<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>



thank you in advance! :)/>

Is This A Good Question/Topic? 0
  • +

Replies To: Attempting to add multiple records to MYSQL using form

#2 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2766
  • View blog
  • Posts: 8,072
  • Joined: 15-January 14

Re: Attempting to add multiple records to MYSQL using form

Posted 03 March 2015 - 03:35 PM

It looks like you're cloning the form, which is going to create several forms with the same ID. You can only have one element per ID, IDs need to be unique. When you get the form data by ID to serialize it's only getting one form with that ID. Instead of cloning the form you should wrap the form elements inside a container element and then clone that container, but make sure you also put the new fields inside the form.
Was This Post Helpful? 0
  • +
  • -

#3 sonia610   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 02-March 15

Re: Attempting to add multiple records to MYSQL using form

Posted 03 March 2015 - 03:41 PM

thank you for your response. could i ask what you mean by put new fields inside the form? i only have two fields one which is readonly (the course code) and then the title

This post has been edited by Dormilich: 04 March 2015 - 01:18 AM

Was This Post Helpful? 0
  • +
  • -

#4 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2766
  • View blog
  • Posts: 8,072
  • Joined: 15-January 14

Re: Attempting to add multiple records to MYSQL using form

Posted 03 March 2015 - 04:26 PM

You should only have 1 form that you're trying to submit. Instead of cloning the form and making a separate form, you should clone what is inside the form (the fields that you're trying to submit) and put another set of fields in the same form.
Was This Post Helpful? 0
  • +
  • -

#5 Christopher.Burkhouse   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 03-March 15

Re: Attempting to add multiple records to MYSQL using form

Posted 04 March 2015 - 12:26 AM

Correct me if I'm wrong, but it appears as if you want a user to essentially be able to say "add another form" and submit two, three, or four forms (or more) at a time.

Not sure if this will help, but you can have multiple repeats of the same input name by adding [], like you would an array in PHP. So for example...

HTML:
...
Form1<br>
Name: <input type="text" name="name[]"><br>
<br>
Form2<br>
Name: <input type="text" name="name[]"><br>
...


PHP:
...
foreach ($_POST['name'] as $val) {
    echo $val;
}
...



I mean that's a rough sample... if it's even going in the right direction. What you need is a bit unclear.

Also make sure you validate data before putting it directly into the database. Seems like you don't even check for empty fields (but I could be misreading the code, I'm a bit tired atm).

Let me know if that helped at all, or if I'm completely off.. and if you have any additional questions.

-Chris
Was This Post Helpful? 0
  • +
  • -

#6 sonia610   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 02-March 15

Re: Attempting to add multiple records to MYSQL using form

Posted 04 March 2015 - 02:48 AM

@Christiopher

the reason i did not add the [] notation was because this affected the form submission so PHP did not know what information to take. I tried this before and was unsuccessful

In essence what i am trying to do is to show the user a form and then allow them to add more rows by clicking the 'add another row' button and wanted to loop through the form submitted and take all the values provided for course_title and add them in one by one into the MYSQL database.

I'm not sure whether my approach to appending additional rows is correct as @ArtificialSoldier suggested.
I want to find the cleanest way to achieve this. if adding multiple forms is an easier way to achieve this then i will probably go ahead with that.

thanks
Was This Post Helpful? 0
  • +
  • -

#7 Christopher.Burkhouse   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 03-March 15

Re: Attempting to add multiple records to MYSQL using form

Posted 04 March 2015 - 05:08 PM

Here's a script I scraped together which uses the [] notation as well as 'add another field' IF you do consider giving it another go. To me it sounds like your best and cleanest option, since you have a single form nice and clean going in and being submitted.

http://christopherbu...tiple_forms.php

I included both the demo and raw format. It's just a very rough example. What I will say straight up on my example is that the javascript is not to be used as a good example. When you click "Add Another Phone#", it empties all phone numbers, but that's because of the JS I used as a rough sample. What I wrote this for is to show you how [] notation is used between HTML and PHP.

I think jQuery actually has something for appending a new form without clearing out the other fields, but could be wrong about that.

If this helps be sure to vote up! If not, then sorry ):

BTW the biggest thing to take from this is [] notation in HTML is read in as an array, so phone[] five times is read in as $_POST['phone'][0] $_POST['phone'][1] $_POST['phone'][2] $_POST['phone'][3] and $_POST['phone'][4]. If you try to print $_POST['phone'], you'll just see 'Array.' I imagine running it through SQL would give an error or Array in its place, not sure what exactly happened in your case.
Was This Post Helpful? 1
  • +
  • -

#8 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2766
  • View blog
  • Posts: 8,072
  • Joined: 15-January 14

Re: Attempting to add multiple records to MYSQL using form

Posted 05 March 2015 - 09:59 AM

It sounds like jQuery's serialize method might break that. There are some workarounds here:

http://stackoverflow...ent-is-an-array
Was This Post Helpful? 1
  • +
  • -

#9 sonia610   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 02-March 15

Re: Attempting to add multiple records to MYSQL using form

Posted 06 March 2015 - 02:52 PM

Thank you both for your help. I have managed to get it working after using both of your advices!

much appreciated :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1