achll
achll

Reputation: 163

get textarea value, separate by new line, save to database php

I have a textarea in my html named add-list. I want to get the value of the textarea per line break and then save it to my database. The problem is, when it saves the input to the database, the second and succeeding entries have a whitespace before the input.

Here is my function for getting the value:

public function add(){
        $checker = false;
        $names = $this->input->post('add-list');

            if (strpos($names, "\n") == TRUE ) { //newline found
                $names = nl2br(trim($this->input->post('add-list')));
                $namesArray = explode('<br />', $names);

                foreach($namesArray as $name) {
                    $checker = false;
                    $checker = $this->checkDatabase($name); //check if name already exists in database
                    if ($checker) {
                        echo "<script type='text/javascript'>alert('A site in your list already exists. Duplicate sites are not allowed.');</script>";
                    }

                    if (!$checker) {
                        $this->data_model->addCommunity($name);
                    }
                }

                $this->index();
                redirect(base_url());
            }

            else if (strpos($names, "\n") == FALSE) {
                $checker = $this->checkDatabase($names);
                if ($checker) {
                    echo "<script type='text/javascript'>alert('" . $names . " already exists. Duplicate sites are not allowed.'); window.location.href='".base_url()."'</script>";
                }

                if (!$checker) {
                    $this->data_model->addCommunity($names);
                    $this->index();
                    redirect(base_url());
                }
            }
    }

What I get in my database is like this:

firstName
 secondName //there's a whitespace before 's'

Help me please!!!

Upvotes: 0

Views: 2876

Answers (1)

Matthias W.
Matthias W.

Reputation: 1077

Why do you go all the way through nl2br and then explode instead of using explode with a line break? But just use the search or a search engine, e.g. Explode PHP string by new line (long time no PHP, so I might not be quite right).

Upvotes: 1

Related Questions