Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

MySQL Insert Query on dynamically generated form fields

MySQL Insert Query on dynamically generated forms.  I'm not 100% sure how to ask this question.  I have a form that has a field group of Name, Address, email and phone.
These are under a specific contact organization.  I can dynamically add a new field and add a new name, Address, email and phone.  On and on.  I need to insert each one of these contacts into my DB on a new line.  They will of course have a unique ID but the same record_id of the name before them.  I'm not sure how to write this.  Also, in my form, do I write the name like below so as to create the array?

Help?

 $arr = array();
            for ($index = 0; $index < count($name); $index++) {
                $arr[$index] = $name[$index] . " " . $email[$index] . " " . $phone[$index] .;
            }


<html>
    <div class="col-12 col-print-7">
                                        <div class="">
                                            <label for="">Name:</label>
                                            <textarea data-gramm_editor="false"  data-gramm_editor="false" name="name[]" value="<?= $ii_firstname ?>" ></textarea>
                                        </div>
                                    </div>
 

                                    <!--  START Email  -->
                                    <div class="col-12 col-print-7">
                                        <label for="">Email:</label>
                                        <textarea data-gramm_editor="false"  name="email[]" value="<?= $email ?>" ></textarea>
                                    </div>
                                    <!--  END Email  -->

                                    <!--  START Phone  -->
                                    <div class="col-12 col-print-7">
                                        <label for="">Phone:</label>
                                        <textarea data-gramm_editor="false"  name="phone[]" value="<?= $phone ?>"></textarea>
                                    </div>



//  THIS IS WHAT I HAVE RIGHT NOW 
I hope this helps:
      $entity_type = 'Surgeon Assistant';
            $sequence_no = isset($_POST['sequence_no']) ? $_POST['sequence_no'] : '';
            $name = isset($_POST['ii_pi_name1']) ? $_POST['ii_pi_name1'] : '';
            $email = isset($_POST['ii_pi_email1']) ? $_POST['ii_pi_email1'] : '';
            $phone = isset($_POST['ii_pi_phone1']) ? $_POST['ii_pi_phone1'] : '';
            $work_phone = isset($_POST['ii_pi_work_phone']) ? $_POST['ii_pi_work_phone'] : '';
            $cell_phone = isset($_POST['ii_pi_cell_phone']) ? $_POST['ii_pi_cell_phone'] : '';


            $insert_assistant = array('record_id' => $id,
                'parent_id' => $seller_id,
                'date' => $date,
                'entity_type' => $entity_type,
                'sequence_no' => $sequence_no,
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'work_phone' => $work_phone,
                'cell_phone' => $cell_phone,
            );
            if ($this->input->post('id')) {
                $id = $this->main_data_model->update($insert_assistant, $this->input->post('id'));
            } else {
                $id = $this->main_data_model->insert($insert_assistant);
            }

Open in new window


PS, sorry for the High Priority.  I have someone breathing down my neck.
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

You're on the right lines with naming your form fields using an array.

When you name your fields like this, you effectively receive the data as an array at the server side, so assume you have this in your HTML

<input type="text" name="email[]">
...
<input type="text" name="email[]">
...

When your form is POSTed to the server, the value in the $_POST['email'] variable would be an array, so you would need to loop over:

foreach ( $_POST['email'] as $email ):
   // do something with each $email
endforeach;

Open in new window

Using the array syntax actually means that you can be a bit smarter with naming your fields to make it easier to manage at the server-side. For example, take a look at the following HTML:

<input type="hidden" name="id">

<input type="text" name="user[1][email]">
<input type="text" name="user[1][firstname]">
<input type="text" name="user[1][lastname]">

<input type="text" name="user[2][email]">
<input type="text" name="user[2][firstname]">
<input type="text" name="user[2][lastname]">

<input type="text" name="user[3][email]">
<input type="text" name="user[3][firstname]">
<input type="text" name="user[3][lastname]">

Open in new window

What this now means is that you can loop over your data in a more meaningful way:

foreach ( $_POST['user'] as $user ):
    // $user is now an array containing email, firstname, lastname
    echo $user['firstname'];
    echo $user['lastname'];

    // you could even pass the whole array into your DB if you wanted (do some sanity checks first though!)
    $id = $this->main_data_model->insert( $user );
endforeach;

Open in new window

Avatar of Robert Granlund

ASKER

This is where I am at the moment but everything is being entered as NULL.


Controller:
 $entity_type = 'Surgeon Assistant';
            $sequence_no = '';
            $name = isset($_POST['ii_pi_name']) ? $_POST['ii_pi_name'] : '';
            $email = isset($_POST['ii_pi_email']) ? $_POST['ii_pi_email'] : '';
            $phone = isset($_POST['ii_pi_phone']) ? $_POST['ii_pi_phone'] : '';
            $work_phone = isset($_POST['ii_pi_work_phone']) ? $_POST['ii_pi_work_phone'] : '';
            $cell_phone = isset($_POST['ii_pi_cell_phone']) ? $_POST['ii_pi_cell_phone'] : '';


            $insert_assistant = array('record_id' => $id,
                'parent_id' => $seller_id,
                'date' => $date,
                'entity_type' => $entity_type,
                'sequence_no' => $sequence_no,
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'work_phone' => $work_phone,
                'cell_phone' => $cell_phone,
            );
            if ($this->input->post('id')) {
                $id = $this->main_data_model->update($insert_assistant, $this->input->post('id'));
            } else {
                $id = $this->main_data_model->insert_sa($insert_assistant);
            }

Open in new window


Model
 function insert_sa($value) {
$i=0;
        foreach ($value as $contact) {
            $data[] = array(
                'record_id' => $contact['id'],
                'parent_id' => $contact['seller_id'],
                'date' => $contact['date'],
                'name' => $contact['name'],
                'phone' => $contact['phone'],
                'entity_type' => $contact['entity_type'],
                'sequence_no' => $i,
                'name' => $contact['name'],
                'email' => $contact['email'],
                'phone' => $contact['phone'],
                'work_phone' => $contact['work_phone'],
                'cell_phone' => $contact['cell_phone']
            );
            $i=$i+1;
        }


        $this->db->insert_batch($this->table_name, $data);
        $insert_id = $this->db->insert_id();
       // echo $this->db->last_query(); die;
        return $insert_id;

Open in new window


View
   <div class="row">
                                    <div class="col-12 col-print-7">
                                        <label for="">Name:</label>
                                        <textarea data-gramm_editor="false"  name="ii_pi_name[]" value="<?= $ii_pi_name1 ?>" ></textarea>
                                    </div>

                                    <div class="col-12 col-print-7">
                                        <label for="">Email:</label>
                                        <textarea data-gramm_editor="false"  name="ii_pi_email[]" value="<?= $ii_pi_email1 ?>" ></textarea>
                                    </div>
                                    <!--  START Phone  -->
                                    <div class="col-12 col-print-7">
                                        <label for="">Phone:</label>
                                        <textarea data-gramm_editor="false"  name="ii_pi_phone[]" value="<?= $ii_pi_phone1 ?>"></textarea>
                                    </div>
                                    <div class="col-12 col-print-7">
                                        <label for="">Work Phone:</label>
                                        <textarea data-gramm_editor="false"  name="ii_pi_work_phone[]" value="<?= $ii_pi_work_phone ?>"></textarea>
                                    </div>
                                    <div class="col-12 col-print-7">
                                        <label for="">Cell Phone:</label>
                                        <textarea data-gramm_editor="false"  name="ii_pi_cell_phone[]" value="<?= $ii_pi_cell_phone ?>"></textarea>
                                    </div>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Nothing seems to be entering into my DB.  I have turned on error reporting and it is in a form.
I'm getting the error:
A PHP Error was encountered
Severity: Notice

Message: Undefined property: Login::$post

Filename: controllers/login.php

Line Number: 253

A PHP Error was encountered
Severity: Notice

Message: Trying to get property of non-object

Filename: controllers/login.php

Line Number: 253

Line 253 is: if ( is_array( $this->post->contact ) ):
Sorry - I'd made a typo in the code I posted, which I've now corrected. Instead of:

$this->post->contact

it should read

$this->input->post('contact')

And that will only work if you've named your <input> fields correctly ie. contact[1][email] etc.
I actually figured that one out on my own.  However, I am not getting any errors and nothing is going into the DB.  I will keep looking.
OK. It makes sense if you work through this step by step. First step is to make sure you're actually getting the correct data sent through to your php script. Create a very simple controller method:

public function test() {
    var_dump( $this->input->post() );
}

Open in new window

And then set your HTML form's action to that method <form method="post" action="test">. Submit your form and check the output.

Once you know that's working, then expand on it by building your $contacts array in the controller method and var_dumping that. Once you know that's all OK, then make the call to the Model.
When I add an action to the form it does not show up.
Not sure what you mean. You form must be posting somewhere! You set this by using the action attribute of the form. What you set it to will depend on your CodeIgniter setup and how you have your controllers configured. If you don't set an action, then it will get posted back to the same controller method that you use to call the view.
It is strange, the coe someplace is adding the user id on to the query and I had not accounted for that in the insert.
That seems to have done the trick.  One final thing, I have inherited this form.  What do you think the best way to insert the value, after looking at the way they have it?  Taking into consider the new array format.

<html>
         <div class="col-12">
                                        <label for="">Email:</label>
                                        <textarea data-gramm_editor="false"  name="dme[1][di_email]" value="<?= $di_email ?>"></textarea>
                                    </div>

                                    <!--  START phone  -->
                                    <div class="col-12 col-print-7">
                                        <label for="">Phone:</label>
                                        <textarea data-gramm_editor="false"  name="dme[1][di_phone]" value="<?= $di_phone ?>"></textarea>
                                    </div>
                                    <div class="col-12 col-print-7">
                                        <label for="">Work Phone:</label>
                                        <textarea data-gramm_editor="false"  name="dme[1][di_work_phone]" value="<?= $di_work_phone ?>"></textarea>
                                    </div>
                                    <div class="col-12 col-print-7">
                                        <label for="">Cell Phone:</label>
                                        <textarea data-gramm_editor="false"  name="dme[1][di_cell_phone]" value="<?= $di_cell_phone ?>"></textarea>
                                    </div>

Open in new window

Here is a basic working sample
Form
  <form action="t3554.php" method="post">
    <div class="address-block">
      <h2>Client Addresses <span class="addaddress float-right">+</span></h2>
      <div class="address-list">
        <div class="address-item">
          <h3>Address 1</h3>
          <div class="row">
            <label class="col-md-3">Name</label>
            <div class="col-md-9"><input type="text" class="form-control" name="name[]"></div>
            <label class="col-md-3">Email</label>
            <div class="col-md-9"><input type="text" class="form-control" name="email[]"></div>
            <label class="col-md-3">Address</label>
            <div class="col-md-9"><input type="text" class="form-control" name="address[]"></div>
            <label class="col-md-3">Phone</label>
            <div class="col-md-9"><input type="text" class="form-control" name="phone[]"></div>
          </div>
        </div>
      </div>
      <div class="text-left mt-1">
        <button class="btn btn-primary">Submit</button>
      </div>
  </form>

Open in new window

jQuery
<script>
$(function() {
  $('.addaddress').click(function() {
    var removeBtn = $('<a>', {class: 'remove-address'}).text('x');
    var cln = $('.address-list div:first-child').clone();
    cln.prepend(removeBtn);
    $('.address-list').append(cln);
    setHeadings();
  });
  $('form').on('click', '.remove-address', function(e) {
    e.preventDefault();
    $(this).closest('.address-item').remove();
    setHeadings();
  });
  
  function setHeadings()
  {
    $('.address-item h3').each(function(i, e) {
      if (i == 0) return;
      this.innerHTML = 'Address ' + (1+i);
    });
  }
});
</script>

Open in new window

PHP
<script>
$(function() {
  $('.addaddress').click(function() {
    var removeBtn = $('<a>', {class: 'remove-address'}).text('x');
    var cln = $('.address-list div:first-child').clone();
    cln.prepend(removeBtn);
    $('.address-list').append(cln);
    setHeadings();
  });
  $('form').on('click', '.remove-address', function(e) {
    e.preventDefault();
    $(this).closest('.address-item').remove();
    setHeadings();
  });
  
  function setHeadings()
  {
    $('.address-item h3').each(function(i, e) {
      if (i == 0) return;
      this.innerHTML = 'Address ' + (1+i);
    });
  }
});
</script>

Open in new window

Working sample here
Not sure what you mean by 'best way to insert the value'. Can you explain.
Once the value has been set, after the POST show it in the value?  
my naming conventions are like so:
name="dme[1][di_email]" value=""  How do I write if(isset($_POST[di_email][1]'

The currently have in the value: <?= $di_email ?>
If you're posting your form using AJAX, then you don't need to because the user never leaves the page. Whatever they type in will remain. Obviously if they click on the Submit button again, then you script would re-fire and you'd end up inserting duplicate records into your DB.

If you're wanting to re-generate the page (either because you're not using AJAX or the page is re-visited), then you'd need to query your DB to get the results and then loop over the results - outputting the HTML inside the loop. In CodeIgniter, you would generally call a Model's method to retrieve all the results and then pass that into your view. Something lke this:

//Controller method
function ViewResults() {
    $contacts = $this->main_data_model->get_all_contacts();
    $this->load->view( "myView", array( 'contacts' => $contacts ) );
}

Open in new window


Then your view would have a access to a variable called $contacts containing an array of records, so you'd loop over that:

<?php foreach ( $contacts as $contact ): ?>
<div>
    <p><?= $contact->name ?></p>
    <p><?= $contact->email ?></p>
    <p><?= $contact->phone ?></p>
</div>
<?php endforeach; ?>

Open in new window

This was a hug help and a great learning curve.  My brain hurts
haha. If your brain hurts, then you're doing something right ;)