简体   繁体   中英

Save lines from textarea to database

My goal is to extract each line from a textarea and save it to my mysql db.

I think my problem lies within the AJAX function or the part, where I get the lines from the textarea, but see yourself:

//#userip = textarea;


    var content = $("#user_ip").val();
    var ips = content.split("\n");

    $.ajax({
        type:       'POST',
        url:        'inc.php?ban_user',
        data:       'user_ip='+ips,
        dataType:   'html',
        success:    function(data) {
            alert(data);
        },
            error: function() {
                alert("Error");
        }
    });

And the PHP part is:

        if (isset($_POST["user_ip"])) {

        $user_ip   = htmlspecialchars(trim($_POST["user_ip"]));

            mysql_query("INSERT into banned (ip) values ('$user_ip')") or die(mysql_error());

        echo($user_ip);

    }

At this point $user_ip seems to be just one string of all textarealines combined.

I know that this way the php code above wont work and it will save all lines as one result!

What I want: Save each txtarea-line seperatly in my db.

"data" attribute want an object with "attribute":value pairs, and your give him a string.

$.ajax({
        type:       'POST',
        url:        'inc.php?ban_user',
        data:       {'user_ip': ips},
        dataType:   'html',
        success:    function(data) {
            alert(data);
        },
            error: function() {
                alert("Error");
        }
    });

Don't split the user entered string on client side (ajax) but within the php script.

if (isset($_POST["user_ip"])) {
  $user_ip   = explode("\n",htmlspecialchars(trim($_POST["user_ip"])));
  foreach ( $user_ip AS $uip ) {
    mysql_query("INSERT into banned (ip) values ('$uip')") or die(mysql_error());
    echo($uip);
  }
}

I would do this with the following method call:

$lines = preg_split( '/\r\n|\r|\n/', $string );

This will give you an array of all lines in the text. After this you only need to iterate thru it and add every value to the database.

your problem lies within this:

var ips = content.split("\n");

split() returns an array of all the strings.

It would have been helpful if you'd showed us what $_POST["user_ip"] contained.

The $.val() method returns the value from the first element in a set - so it won't work with multiple textareas (if that's what you think it does).

You get the string value and convert it to a line-by line array of strings, then are doing an implicit conversion back to a single string - why? Just send the 'content' value to your script then split by newline there.

(and BTW, the code will still be vulnerable to SQL injection).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM