Frage

Going mad trying to work out where I am going wrong here

I am getting the error message:

trim() expects parameter 1 to be string, array given

which I know I am getting because an array is being sent and it is waiting for a string.

I have a multi selection box which I am populating from a database, also if anyone can work out how to retain the selections after a failed page submit I would also appreciate it.

I am using this $trimmed = array_map('trim', $_POST);all my other form inputs are fine but because this is a multi select box and its creating an array it causes an error.

Anyone know the way around this?

<select name="special[]" id="special" multiple="multiple" style="width: 700px; height: 180px;"    >

         <?php
        $q_climbingSpecial = "SELECT climbingspecial.climbingspecial FROM climbingspecial ORDER BY climbingspecial ASC";
        $result_climbingSpecial = mysqli_query ($dbc,$q_climbingSpecial);

        if (mysqli_num_rows($result_climbingSpecial) > 0){

        while ($row_climbingSpecial = mysqli_fetch_array($result_climbingSpecial,MYSQLI_ASSOC)){

        echo "<option value=\"$row_climbingSpecial[climbingspecial]\"";


        echo "selected=\"selected\""; 

        echo ">$row_climbingSpecial[climbingspecial]</option>\n"; 
        }


        }

        ?>   



        </select> 
War es hilfreich?

Lösung

in stead of using array_map, you will have to fallback to writing your own code, and checking if you are facing an array inside the $_POST array.

if (isset($_POST))
    foreach($_POST as $key=>$val)
        if (is_array($val))
            foreach($val as $key2=>$val2)
                $_POST[$key][$key2] = trim($_POST[$key][$key2]);
        else
            $_POST[$key] = trim($_POST[$key]);



And to retain the selections after a failed page submit, you need to change:

echo "selected=\"selected\"";

into

if (isset($_POST) && isset($_POST['special']) && is_array($_POST['special']))
    foreach($_POST['special'] as $key3=>$val3)
        if (trim($row_climbingSpecial['climbingspecial']) == trim($val3))
        {
            echo "CHECKED=\"CHECKED\""; // it's 'checked', not 'selected' for check box.
            break;
        }



And by the way, you also need to change

echo "<option value=\"$row_climbingSpecial[climbingspecial]\"";

into

echo "<option value=\"{$row_climbingSpecial['climbingspecial']}\"";

the apostrophes ' prevent notices about undefined constants being taken for a string and the braces {} allow earlier versions of php to recognizing the called array key inside the variable.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top