Getting Multiple Array Form Values With PHP

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.

Published by

Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

17 thoughts on “Getting Multiple Array Form Values With PHP”

  1. @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/

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

  3. @charles

    You’d simply use thew ‘files’ array, instead of the ‘post’ array. E.g. assuming you’re using a file input called ‘the_file’ and have added enctype=”multipart/form-data” to your form tag, you’d access the file name of a particular file like:

    $file_name = $_FILES[“the_file”][“name”][$i];

    hope that helps! 🙂

  4. HI great tutorial, including the adding unlimited form fileds one.

    I have one problem when comes to adding the values to the database. I seem to have got it so USER 1 is entered OK, I also have it so that if I add 3 websites they are all entered as such going thru the for loop.

    websiteID website_url website_title
    1 1 t1
    2 2 t2
    3 3 t3

    the problem comes when the website ID ar give a user ID, the websites 2 & 3 are given a 0 user ID

    here is my code, any help to get the user ID added to the 2 and 3 records woud great
    ===========
    if (isset($_POST[‘fields’])) {

    for ( $i=0;$ilast_insert_id();

    $sql_website = sprintf(“INSERT INTO websites (Website_URL, Website_Title) VALUES (‘%s’,’%s’)”,
    mysql_real_escape_string($fields),
    mysql_real_escape_string($fields2));
    $result_website = $db->query($sql_website);
    $inserted_website_id = $db->last_insert_id();

    //Insert into users_websites_link table
    $sql_users_website = sprintf(“INSERT INTO users_websites_link (UserID, WebsiteID) VALUES (‘%s’,’%s’)”,
    mysql_real_escape_string($inserted_user_id),
    mysql_real_escape_string($inserted_website_id) );
    $result_users_website = $db->query($sql_users_website);

    ==========

  5. sorry it seems to leave the code out but I have a the if and for you illustrate above to get the $fields and $fields2 variables

    it must have some to do with the last insert id line? I can’T work it out

    $inserted_user_id = $db->last_insert_id();

  6. soory again, my last comment woked it out, I had to put the “$inserted_user_id = $db->last_insert_id();” outside the loop!

    cheers

  7. Thank you very much. You know what, your posting really saved me from headache and heartache. I really appreciate what you have posted on your website.

    You are awesome man, uber cool! “-)

  8. sir can you provide me with a full tutorial applying this code of you. im trying to work with a multiple textfield but i cant understand it fully. please sir provide me a downloadable tutorial. thank you. im just newbie sir

      1. i really appreciate this Rob.
        how do i set the jquery for more field

        var count = 0;
        $(function(){
        $(‘p#add_field’).click(function(){
        count += 1;
        $(‘#container’).append(
        name #’ + count + ‘
        + ”,
        email #’ + count + ‘
        + ” );

        });
        });

        is the above correct?
        what of the php?
        if (isset($_POST[‘fields’])) {

        //get last inserted userid
        $inserted_user_id = $db->last_insert_id();

        //Loop through added fields
        if (isset($_POST[‘fields’])) {
        for ( $i=0;$iquery($sql_website);
        $inserted_website_id = $db->last_insert_id();
        i will highly appreciate your response. thanks

  9. hola, yo deseo saber como puedo obtener el valor de un input, con nombre category_description[1][name], mas o menos lo hago asi:

    var nombre=$(“input:text[name=’category_description[1][name]’]”).val();

    pero no funciona!! necesito ayuda

Leave a Reply

Your email address will not be published. Required fields are marked *