I have some code, a foreach loop, that iterates through a $_post array but I have only just learnt that the foreach loop changes spaces to underscores so on usernames with spaces it is not working.

for example..

The form sends this...

<input name='".$row['username']."' type='checkbox' value='yes' />

and the processing script does this...

foreach($_POST as $username => $value){
    $sql = $database->connection->prepare("UPDATE ".TBL_USERS." SET USERLEVEL = '3' WHERE username = '$username'");
    $sql->execute();

IS there any other way to do this? I cant using strtr or such like as there may be cases where users have underscores and I wont want these being replaced with spaces.

    Foreach does not convert spaces to underscores, that is happening somewhere else. Are you maybe using a framework that attempts to convert user data in $_POST to 'safe' versions?

    If not, maybe it's the browser that is making the conversion to the value in your input. Use a DOM inspector to look at this and see, and test to see if it is also happening in other browsers or not.

      Hi Ashley, are you sure they are not replaced. See here , bearing in mind I am using the foreach on the $_POST array. There is nothing else going on in the script. When I view source of the original input tag the space is there. The form is submitted and then the function is called. If I echo the $username variable (created by the foreach iteration) I see the underscore has been added.

        That may be either the browser or the PHP post/get pre-processing. In any case, since checkboxes are only transmitted if checked, my recommendation would be to set the user name in the input element's "value" attribute instead of its "name" attribute, which I would then instead give an array-style name:

        "<input name='user_name[]' type='checkbox' value='".$row['username']."' />"
        

        Then in your processing code:

        foreach($_POST['user_name'] as $username) {
            $sql = $database->connection->prepare("UPDATE ".TBL_USERS." SET USERLEVEL = '3' WHERE username = '$username'");
            $sql->execute();
        }
        

          Very sure, the page you linked says that the behaviour is part of PHP (which I wasn't aware of until now) but not the foreach (I created a simple local test script to prove this)

          I would probably avoid having spaces in the name of an element anyway, as it can cause problems as you've seen with PHP, and also any Javascript you're using to interact with those input elements

            Thank you both for your help. NogDog, your idea worked perfectly. Many thanks.

              Write a Reply...