简体   繁体   中英

PHP & MYSQL Insert into database with a textarea (new line & new line into database)?

 <?php
require 'db2.php';
?>
<html>
<form action="" method="POST">
<textarea rows="5" cols="80" id="proxies" name="proxies">
</textarea>
<input type="submit" name="insert" value="Insert">
</form>
</html>
<?php
if (isset($_POST['insert']))
{
$string = $_POST['proxies'];
$arrray = explode(':',$string);
$proxy = $arrray[0] . ':' . $arrray[1];
$country = $arrray[2];
$state = $arrray[3];
$city = $arrray[4];
$query = mysqli_query($link,"INSERT INTO `proxies`(`proxy`,`country`, `state`, `city`) VALUES ('{$proxy}', '{$country}', '{$state}', '{$city}')");
}
?>

So basically, I'm confused I thought this would add every new line, but obviously I was wrong.

How would I get this text area to submit into my database line per line like eg

If I entered this into the text area

test:80:test:test:test
test:80:test:test:test
test:80:test:test:test
test:80:test:test:test

It'll add all of those 4 records, cheers!

use this code :

 $text = trim($_POST['textareaname']); 
    $textAr = explode("\n", $text);  // remove the last \n or whitespace character
    $textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind

    foreach ($textAr as $line) {
        // processing here. 
    } 

for more explanation see this question .

Please try this code:

$string = trim($_POST['proxies']);
$stringArray = explode("\n" , $string);
$stringArray = array_filter($stringArray,'trim');

foreach($stringArray as $ $string){
$arrray = explode(':',$string);
$proxy = $arrray[0] . ':' . $arrray[1];
$country = $arrray[2];
$state = $arrray[3];
$city = $arrray[4];
$query = mysqli_query($link,"INSERT INTO `proxies`(`proxy`,`country`, `state`, `city`) VALUES ('{$proxy}', '{$country}', '{$state}', '{$city}')");
}

I would recommend you to append

PHP_EOL 

PHP_EOL - is a End of line constant in PHP, Append that at the end of string instead of '\\n'

I hope it will solve the problem,

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