Search code examples
phparraysformsimplode

no values in my string from an imploded post array? PHP


Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.

HTML form

<html>
<head>
<title>EMS</title>
</head>

<body>
<h1>EMS - Add New Employees</h1>

<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td>  <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td>  <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td>  <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>

I want to implode the 4 elements in the $_POST["data submitted"] array to a string.

PHP

<?php


    if (isset($_POST['data_submitted'])){ 



       $employee = implode(",",$_POST['data_submitted']);



        echo "employee = ".$employee;
    }


?>

Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.

$employee = implode(",",$_POST);

The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee

It contains the name,pps,pin,dob and this ADD New Employee value? How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?


Solution

  • If you wish to implode the submitted data, then you need to refer to the specific items, as follows:

    <?php
    $clean = [];
    
    if (isset($_POST['data_submitted'])){ 
    
     // one way to deal with possibly tainted data
     $clean['name'] =  htmlentities($_POST['name']);
     $clean['ppsn'] =  htmlentities($_POST['ppsn']);
     $clean['pin']  =  htmlentities($_POST['pin']);
     $clean['dob']  =  htmlentites($_POST['dob']);
    
    
     $employee = implode(",",$clean);
     echo "employee = $employee";
    }
    

    Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.

    Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.