Search code examples
phppostvariable-variables

Check if variable name in Post array contains text using PHP


I have a form that allows the user to add more fields if they need them. When the user does this, two more fields appear (one for link text, the other for the link address). I'm use javascript to append a number onto the input names (e.g. newLinkTitle1 + newLinkAddress1, newLinkTitle2 + newLinkAddress2, etc.).

  <input type="text" value="" name="newLinkTitle" size="50" />
  <input type="text" value="http://" name="newLinkAddress" size="50" />  

I want to check if there are variables in my POST array containing the prefix newLinkTitle and then get the newLinkAdress associated with it then add them to my database.

Currently I have this:

foreach ((strpos($_POST, 'newLinkTitle')) as $currentNewLinkTitle) { // check if newLinkTitle exists
    $num = substr($currentNewLinkTitle, 12);  // get the number following "newLinkTitle"
    $currentLinkAddress = $_POST['newLinkAddress'.$num];
    //Update query 

}

Solution

  • The right approach would be to name the fields as arrays: newLinkTitle[] and newLinkAddress[]:

    <input type="text" value="" name="newLinkTitle[]" size="50" />
    <input type="text" value="http://" name="newLinkAddress[]" size="50" />
    

    Then using Your JS code just add another couple of the fields with the very same names (newLinkTitle[] and newLinkAddress[]). And in PHP, just do something like:

    foreach($_POST['newLinkTitle'] as $key => $val) {
        $currentNewLinkTitle = $val;
        $currentNewLinkAddress = $_POST['newLinkAddress'][$key];
        // save to DB
    }
    

    Do not forget to escape the values properly prior to saving to DB!