Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

Using data retrieved from a form submission in another form [PHP]

I have a small form that allows a user to look up user data, they just enter the user ID and it retrieves data from a series of tables and displays this data.

The logic I was going for was press one button to get data, press another to use it.

Here is the form:

enter image description here

One button on the form is called Get data and the other is called Onboard this user.

So each button has a really basic

if(isset($_POST['nameofbutton']))
{   
    // Get data
}

if(isset($_POST['nameofbutton']))
{   
    // Send data
}

One button gets the data using this script

if(isset($_POST['submit']))
{   
    // Set some variables if necessary
    $id = $_POST['id'];

    // Write sql statement with ? as placeholders for any values
    $sql = "SELECT * 
            FROM tblInvestor 
            LEFT JOIN tblReyker ON tblInvestor.invUserId = tblReyker.ReyNPI_Id 
            LEFT JOIN tblDeclarations ON tblInvestor.invUserId = tblDeclarations.invUserId 
            WHERE tblInvestor.invUserId = ?";

    // Prepare the SQL statement using the database connection parameter
    if($stmt = $dbconINV->prepare($sql))
    {
        // Bind any necessary variables 
        if($stmt->bind_param('s', $id))
        {
            $result = $stmt->execute();

            // If the statement ran successfully
            if($result)
            {
                $result = $stmt->get_result();

                if($result->num_rows >= 1)
                {
                    while($row = $result->fetch_assoc())
                    {
                        // If there are result get them here
                        //
                        $userId = $row['invUserId'];
                        //
                        $email = $row['invUserEmail'];
                        // [Not Encrypted]
                        $title = $row['invUserTitle'];
                        // [Encrypted]
                        $forename = $row['invUserForename'];
                        // [Encrypted]
                        $surname = $row['invUserSurname'];
                        // [Not encrypted]
                        $countryOfBirth = $row['ReyCountryOfBirth'];
                        //
                        $emailType = $row['ReyEmailType'];
                        //
                        $dateOfBirth = $row['ReyDateofbirth'];
                        //
                        $nationalInsurance = $row['ReyNI']; 
                        //
                        $primaryAddress = $row['ReyPrimaryAddress'];
                        //
                        $primaryTelephone = $row['ReyPrimaryTelephone'];    
                        //
                        $bankAccountDetails = $row['ReyBA'];    
                        //
                        $citizenshipDetails = $row['ReyCitizenship'];
                        //
                        $planType = $row['ReyPlanType'];
                        //
                        $externalPlanId = $row['ReyExtPlanID'];

                        if($forename != "")
                        {
                            $forename = $security->decrypt($forename);
                        }

                        if($surname != "")
                        {
                            $surname = $security->decrypt($surname);
                        }

                        if($dateOfBirth != "")
                        {
                            $dateOfBirth = $security->decrypt($dateOfBirth);
                        }

                        if($nationalInsurance != "")
                        {
                            $nationalInsurance = $security->decrypt($nationalInsurance);
                        }

                        if($primaryAddress != "")
                        {
                            $primaryAddress = $security->decrypt($primaryAddress);
                            $primaryAddressDecoded = json_decode($primaryAddress, true);
                        }

                        if($primaryTelephone != "")
                        {
                            $primaryTelephone = $security->decrypt($primaryTelephone);
                            $primaryTelephoneDecoded = json_decode($primaryTelephone, true);
                        }

                        if($bankAccountDetails != "")
                        {
                            $bankAccountDetails = $security->decrypt($bankAccountDetails);
                            $bankAccountDetailsDecoded = json_decode($bankAccountDetails, true); 
                        }

                        if($citizenshipDetails != "")
                        {
                            $citizenshipDetails = $security->decrypt($citizenshipDetails);
                            $citizenshipDetailsDecoded = json_decode($citizenshipDetails, true);
                        }

                        echo "User ID " . $userId . "<br />";
                        echo "Plan ID " . $planType . "<br />";
                        echo "External Plan ID " . $externalPlanId . "<br />";
                        echo "Email: " . $email . "<br />";
                        echo "Title: " . $title . "<br />";
                        echo "Forename: " . $forename . "<br />";
                        echo "Surname: " . $surname . "<br />";
                        echo "Country of birth: " . $countryOfBirth . "<br />";
                        echo "Email type: " . $emailType . "<br />";
                        echo "Date of birth: " . $dateOfBirth . "<br />";
                        echo "National Insurance Number: " . $nationalInsurance . "<br />";

                        $_SESSION['userId'] = $userId;
                        $_SESSION['planType'] = $planType;
                        $_SESSION['externalPlanId'] = $externalPlanId;
                        $_SESSION['title'] = $title;
                        $_SESSION['forename'] = $forename;
                        $_SESSION['surname'] = $surname;
                        $_SESSION['countryOfBirth'] = $countryOfBirth;
                        $_SESSION['emailType'] = $emailType;
                        $_SESSION['dateOfBirth'] = $dateOfBirth;
                        $_SESSION['nationalInsurance'] = $nationalInsurance;
                        $_SESSION['address'] = $primaryAddressDecoded;
                        $_SESSION['citizenship'] = $citizenshipDetailsDecoded;
                        $_SESSION['telephone'] = $primaryTelephoneDecoded;
                        $_SESSION['bankAccount'] = $bankAccountDetailsDecoded;

                        // Address
                        foreach($primaryAddressDecoded as $addressKey => $addressValue)
                        {
                            echo $addressKey . " " . $addressValue . "<br />";
                        }

                        // Address
                        foreach($citizenshipDetailsDecoded as $addressKey => $addressValue)
                        {
                            echo $addressKey . " " . $addressValue . "<br />";
                        }

                        // Address
                        foreach($primaryTelephoneDecoded as $addressKey => $addressValue)
                        {
                            echo $addressKey . " " . $addressValue . "<br />";
                        }

                        // Address
                        foreach($bankAccountDetailsDecoded as $addressKey => $addressValue)
                        {
                            echo $addressKey . " " . $addressValue . "<br />";
                        }
                    }
                }
                else // the statement returned 0 results
                {
                    // Deal with the nothingness
                    echo "No data found";
                }
            }
            else // the sql didnt execute
            {
                // Somethings gone wrong here
                echo "No execution";
            }
        }
        else // the binding was wrong
        {
            // Check your bindings
            echo "Binding error";
        }   
    }
    else // There was an error preparing the sql statement (its wrong)
    {
        // the sql is wrong
        echo "SQL error " . $dbconINV->error;
    }
}

Some of the data is encrypted so I decrypt it, also some of the data is a JSON array so I use json_decode(). Once I get the data I store it all in the current session.

The other button does an API call using the data in the session

if(isset($_POST['onboard']))
{
    $userId = $_SESSION['userId'];
    $planType = $_SESSION['planType'];
    $externalPlanId = $_SESSION['externalPlanId'];
    $title = $_SESSION['title']; 
    $forename = $_SESSION['forename']; 
    $surname = $_SESSION['surname']; 
    $countryOfBirth = $_SESSION['countryOfBirth']; 
    $emailType = $_SESSION['emailType']; 
    $dateOfBirth = $_SESSION['dateOfBirth']; 
    $nationalInsurance = $_SESSION['nationalInsurance']; 
    $primaryAddressDecoded = $_SESSION['address']; 
    $citizenshipDetailsDecoded = $_SESSION['citizenship']; 
    $primaryTelephoneDecoded = $_SESSION['telephone']; 
    $bankAccountDetailsDecoded = $_SESSION['bankAccount']; 

    // Create an array to work with
    $onboardingData = array(
        // Generic details
        "Title" => $title,
        "Forenames" => $forename,
        "Surname" => $surname,
        "CountryOfBirth" => $countryOfBirth,
        "EmailAddress" => $email,
        "EmailType" => $emailType,
        "BirthDate" => $dateOfBirth,
        "Suffix" => null,
        "NationalInsuranceNumber" => $nationalInsurance,

        // Primary address
        "PrimaryAddress" => $primaryAddress,

        // Additional addresses (as an array)
        "AdditionalAddresses" => null,

        // Primary telephone
        "PrimaryTelephone" => $primaryTelephone,

        // Additional telephone
        "AdditionalTelephone" => null,

        // Bank accounts
        "BankAccount" => $bankAccountDetails,

        // Primary citizenship
        "PrimaryCitizenship" => $citizenshipDetails,

        "AdditionalCitizenship" => null,

        "ExternalCustomerId" => $userId,
        "ExternalPlanId" => $externalPlanId,
        "PlanType" => $planType
    );

    // Ensure the array has data in it
    if(!empty($onboardingData)) 
    {
        // Usually where I do API call
        die(var_dump($onboardingData));
    }
}

My issue is that when I try to add the decoded JSON arrays to the session they are dumped out as Array, so when I try to build $onboardingData the arrays are NULL.

Am I overcomplicating this?

Upvotes: 0

Views: 27

Answers (1)

Matt
Matt

Reputation: 163

PHP Sessions can hold arrays, but bear in mind that PHP does not support objects and handles them through it's own class called "stdClass".

It is not uncommon practice to store JSON Strings as one value and decode them on demand.

$_SESSION['mySession'] = '{"name":"Matt", "bestAnswer":true}';


$mySession = json_decode($_SESSION['mySession'], true); // true because I prefer arrays in PHP
$name = $mySession['name'];

Without my fussy array requirements:

$mySession = json_decode($_SESSION['mySession']);
$name = $mySession->name;

Upvotes: 1

Related Questions