Home > JQuery, PHP > Getting Multiple Array Form Values With PHP

Getting Multiple Array Form Values With PHP

August 18th, 2009 Rob Leave a comment Go to comments
php array code

PHP Arrays

Further to my article on using JQuery to dynamically append form elements, I have come across situations where multiple items should be appended to the form each time, as opposed to a single input in my article (I did this simplicity). For example, at work I’m currently working on an internal system whereby a user needs to add an unlimited amount of client contacts for a client. Pressing the ‘add contact’ link will append 3 fields – one for conatct name, contact telephone and contact email. Each of these fields are named exactly the same way as before (using square brackets at the end of the name E.g. ‘name[]‘) and appended the same way using JQuery.

There are lots of articles floating about explaing how to add fields, but I’ve not yet seen anything explaining how to retreive multiple elements like this.

The only differnce arises when retreiving these multiple values from the PHP’s POST array. In the example I have appended 3 inputs, named cname[], cemail[] and ctel[]. The values of each can be retreived using a slightly enchanced for loop:

if (isset($_POST['cname'])) {
for ( $i=0;$i<count($_POST['cname']);$i++) {
$contactname = $_POST['cname'][$i];
$conatctemail = $_POST['cemail'][$i];
$contacttel = $_POST['ctel'][$i];
}
}

That’s really all there is to it and I’m finding that the latter comes in useful quit regularly in every day projects.

  1. August 20th, 2009 at 14:21 | #1

    Good article. I have been wondering how to this for a while as there are a lot of tutorials on how to add fields, but none explaining how to get the values.

    Web Design India

  2. September 28th, 2009 at 06:26 | #2

    Great!!

    How about SQL?

  3. September 29th, 2009 at 20:18 | #3

    @dudu

    I’m not exactly sure what you mean? My example is based purely on a HTML form, using PHP to read the results. Using MySQL or SQL doesn’t come into it currently :)

    You could of course use the values within the loop to insert into a MS SQL database (as oppossed to MySQL). E.g. you’d have your insert statement within for loop. More on the latter is in a previous article I wrote, see http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/

  4. James
    April 22nd, 2010 at 20:06 | #4

    Thanks for this Rob, working like a gem, however I also have multiple Radio buttons being created and since their name is the same across each addition, you can’t select just one. If that makes sense. Also having trouble with form validation since fields share the same name.

    Any tips would be great!

    Thank you.

  1. No trackbacks yet.