Jump to content

Dynamic Form Fields Array post to mySQL


platzDB

Recommended Posts

In brief, I'm attempting to capture the form data from a dynamic form to a mysql database.

From here:

512403498_dynamicformentry.jpg.22badfc3594c3b3b823f110ebd82777c.jpg

To Here:

870347639_mysqlpettablecolumns.jpg.eb42aadc6e5a85b16b225ddd12daefb3.jpg

The post data looks like this from the form -
DATA SUBMITTED:

Array(

...
[petlist] => [{"Pet Name":"Hal","Pet Type":"Dog","Breed":"Lab","DOB":"02/10/2013","Gender":"Male","Special Needs":"No"},
{"Pet Name":"Bill","Pet Type":"Dog","Breed":"Golden","DOB":"03/20/2015","Gender":"Male","Special Needs":"No"}]
...

)

PHP CODE:

...
$_POST['petlist'];
...

As a non-php or mysql developer, I'm learning on the fly.  This is a section of the php file that I was using to post the form data to mySQL.  This worked great up to the point I added the dynamic form widget.

<?php
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
        foreach ($params as &$var) {
            // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
            is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
            unset($var);
        }
}

// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);     

$submission_id = $_POST['submission_id'];
$formID =$_POST['formID'];
$ip =$_POST['ip'];
$fname =$_POST['fname'];
$lname =$_POST['lname'];
$spousename =$_POST['spousename'];
$address =$_POST['address'][0]." ".$_POST['address'][1]." ".$_POST['address'][2]." ".$_POST['address'][3]." ".$_POST['address'][4]." ".$_POST['address'][5];
... 

$db_host = 'localhost';
$db_username = 'xxxxx';
$db_password = 'xxxxx';
$db_name = 'xxxxx';

mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);

// search submission ID

$query = "SELECT * FROM `tableName` WHERE `submission_id` = '$submission_id'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);

if ($resultcount > 0) {
 
    mysql_query("UPDATE `tableName` SET
                                `fname` = '$fname',
                                `lname` = '$lname',
                                `spousename` = '$spousename',
                                `address` = '$address',
                                 
                                 WHERE `submission_id` = '$submission_id'")
     or die(mysql_error());
   
} else {

    mysql_query("INSERT INTO `tableName` (submission_id, formID, IP, fname, lname, spousename, address)
                               VALUES ('$submission_id', '$formID', '$ip', '$fname', '$lname', '$spousename', '$address') ")
    or die(mysql_error()); 

}
?>

It has been suggested that I explore using the PHP Explode() function.  It's possible that may work, but can't get my head around how to apply the function to the PETLIST Array.

Looking for suggestions or direction to find a solution for this challenge.  Looking forward to any replies.

Link to comment
Share on other sites

27 minutes ago, platzDB said:

It has been suggested

What should be suggested is that you stop using dangerous obsolete mysql code that has been completely removed from PHP and was warned about for well over ten years and to stop running a php version that is hundreds of releases behind and reached end of life long ago. Toss that code in the trash. Every bit of it is bad.

You need to use PDO with Prepared Statements. This tutorial will get you going.

https://phpdelusions.net/pdo

Edited by benanamen
Link to comment
Share on other sites

Looks like your widget is json encoding the form data - you'll need to decode it to process the contents

$pet_data = json_decode($_POST['petlist']['petlist'], true);

which should give you ann array like this

$pet_data = Array
(
    [0] => Array
        (
            [Pet Name] => Hal
            [Pet Type] => Dog
            [Breed] => Lab
            [DOB] => 02/10/2013
            [Gender] => Male
            [Special Needs] => No
        )

    [1] => Array
        (
            [Pet Name] => Bill
            [Pet Type] => Dog
            [Breed] => Golden
            [DOB] => 03/20/2015
            [Gender] => Male
            [Special Needs] => No
        )

)

You will need to reformat your dates before putting into your table (store as yyyy-mm-dd).

Why are you adding slashes to all your data? Use prepared queries with mysqli or PDO (preferred). The mysql_ library you are using is obsolete.

Why checkboxes for pet type? No one has a pet that is both cat and dog!.

Your data column types are overkill.

You'll find it more efficient to use INSERT … ON DUPLICATE KEY UPDATE... than your method of checking if it exists then inserting or updating.

Link to comment
Share on other sites

One other problem I see: It appears there is a single submission_id whether the user submits one or multiple pets (since it is not included in the JSON data). But, the current code is using that submission_id to determine duplicates. If a user was to submit two records. I think you would end up with ONE in the database. The first record submissions would be created as a new record. But, when processing the second submissions, the code would "assume" it was a duplicate because there is an existing record with the same submission_id (i.e. the first record) and it would perform an UPDATE.

I'm not sure where/how the submission_id is being created/managed. But, I think you'll need to change that logic.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.