Jump to content

[SOLVED] Textarea info put into separate rows


shakingspear

Recommended Posts

<?php
$textarea = mysql_real_escape_string($_POST['textarea']);
$array = explode("\n", $textarea);

$i=0;
$value = trim($array[$i]);
if (!empty($value)) {
foreach ($array as $value) {
   mysql_query("INSERT INTO random_prompts (prompt) VALUES ('{$array[$i]}')") or die(mysql_erorr());
   $i++;
}
}
?>

Your are using mysql_real_escape_string which I believe will turn \n into \\n

so try exploding by \\n or \\r\\n

 

but really, you should first explode it and THEN run mysql_real_escape

 

I got this to work!

 

That's almost a mirror image of the solution I posted way back on reply #3. However, in my humble opinion, I think mine was a little more efficient because it would 1) Not insert empty values into the database if the user had empty lines and 2) created a single insert quert as opposed to multiple queries. There were some syntax errors in that code, but the logic was sound. I went ahead and cleaned it up - with comments.

 

//Ensure the POST value is set
if (isset($_POST['textarea']))
{
    //Explode the POST value into an array
    $lines = explode("\n", $_POST['textarea']);

    //Iterate through each line
    foreach ($lines as $line)
    {
        //Trim leading and trailing spaces
        $line = trim($line);
        //If line not empty add to array of values
        if(!empty($line))
        {
            $values[] = '(' . mysql_real_escape_string($line) . ')';
        }
    }

    //If array of values has elements create SQL statement & run
    if (count($values))
    {
        $query = "INSERT INTO random_prompts (prompt) VALUES (" . implode(', ', $values) . ")";
        //echo "<pre>$query</pre>";
        mysql_query($query) or die(mysql_erorr());
    }
}

Link to comment
Share on other sites

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.