Jump to content

Recommended Posts

After a lot of googling yesterday I managed to get a text area to import data into a database for every new line.

 

I noticed today that it imports an extra empty line at the very end of the list in the text area.

 

Here is my code that does the importing:

    $area = array_map('trim', explode("\n", $_POST['area']));
    foreach($area as $line) {
$query = "INSERT INTO QuotationsTBL(Quotation)VALUES('$line')";
if(mysql_query($query)){
}else{
echo "Fail, please try again";}
}

 

Like I said I googled (had to use several different websites including here :) )a lot to figure this out so I don't quite understand how it works ie the array_map('trim' ..ect part

 

Any advice to get rid of that empty line would be wonderful!

 

Link to comment
https://forums.phpfreaks.com/topic/240959-how-to-avoid-empty-line/
Share on other sites

Also cant seem to get it to work... I googled empty() and you cant do emtpy(trim($var))

 

Well after looking at it closer it appers when I would copy&paste my data I would get an empty line at the end, I can delete it and it will not import a blank entry.

 

My question still stands though it would be nice to be able to avoid this on accident.

This will remove explode the textarea on the line breaks, and unset any elements that consist of nothing but a line break. Don't run queries in a loop when it's avoidable, and in this case it is avoidable. After the loop has cleaned up the array, implode it with )', (' as the glue, and then execute the query once with the imploded values. Echo $query to see what the query string looks like . . .

 

$area = explode("\n", $_POST['area']);
foreach( $area as $k => $v ) {
   $v = trim($v);
   if( empty($v) ) {
      unset($area[$k]);
   }
}
$values = implode("'), ('", $area);
$query = "INSERT INTO QuotationsTBL (Quotation) VALUES ('$values')";

 

I prefer to use string functions like above when possible, but another way would be with preg_replace . . .

 

$_POST['area'] = preg_replace("~\n{2,}~", "\n", $_POST['area']);
$area = explode("\n", trim($_POST['area']));
$values = implode("'), ('", $area);
$query = "INSERT INTO QuotationsTBL (Quotation) VALUES ('$values')";

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.