Reputation: 8696
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.
Upvotes: 0
Views: 646
Reputation: 48357
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).
Upvotes: 0
Reputation: 3226
your problem lies within this:
var ips = content.split("\n");
split()
returns an array of all the strings.
Upvotes: 0
Reputation: 1415
"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");
}
});
Upvotes: 1
Reputation: 10303
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.
Upvotes: 0
Reputation: 9022
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);
}
}
Upvotes: 0