Nuri Ensing
Nuri Ensing

Reputation: 2030

selectbox with options which is populated from mysql gets a whitespace/newline

I populate a selectbox from a mysql database:

      <?php
//Query the database for the results we want
                            $queryBesteller = $conn->query("SELECT * FROM bestellers");

//Create an array of objects for each returned row
                            while ($bestellerArray[] = $queryBesteller->fetch_object());

//Remove the blank entry at end of array
                            array_pop($bestellerArray);
                            ?>

   <label for="customerNameLabel">Naam Besteller</label>
                                <select name="bestellers" id="bestellerSelectBox" >
                                    <option>Selecteer Besteller</option>
                                    <?php foreach ($bestellerArray as $option) : ?>

                                        <option  value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
                                    <?php endforeach; ?>
                                </select>

Most of the names are populated like this:

<option value="Harry Parry">Harry Parry</option>

But some also get this, and this is fault:

<option value="Hans Petersonasd
">Hans Petersonasd
</option>

Because i later want to get other data from mysql on basis of the name, but if there is a space then it won't work.

I tried to use trim in Sql but also didnt fix

Answer: I tried trimming like the answers below but that also didn't fix. I deleted the rows from the table and re-added them and then it worked

Upvotes: 0

Views: 28

Answers (3)

ajmedway
ajmedway

Reputation: 1492

I would fix the issue with your data at source by executing this MySQL query:

UPDATE bestellers SET name = REPLACE(TRIM(TRAILING ' ' FROM col_name), 
                                     TRIM(TRAILING '\r' FROM col_name), 
                                     TRIM(TRAILING '\n' FROM col_name),
                                     TRIM(TRAILING '\r\n' FROM col_name));

This will serve to trim newlines and whitespace from the name field in all rows of this bestellers table. The reason that just using TRIM(name) didn't work for you was that newlines are your issue and TRIM() alone only removes whitespaces.

Upvotes: 1

Nuri Ensing
Nuri Ensing

Reputation: 2030

Answer: I tried trimming like the answers below but that also didn't fix. I deleted the rows from the table and re-added them and then it worked

Upvotes: 0

jqheart
jqheart

Reputation: 767

Try,

<?php foreach ($bestellerArray as $option) : ?>

    <option  value="<?php echo trim($option->name); ?>"><?php echo trim($option->name); ?></option>
<?php endforeach; ?>

Upvotes: 1

Related Questions