PHP& MYSQL使用textarea(新行和新行进入数据库)插入数据库?

时间:2014-01-01 23:30:11

标签: php mysql

 <?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}')");
}
?>

所以基本上,我很困惑,我认为这会增加每一条新线,但显然我错了。

如何将此文本区域提交到每行的数据库行,例如

如果我将其输入文本区域

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

它会添加所有这4条记录,欢呼!

3 个答案:

答案 0 :(得分:1)

使用此代码:

 $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. 
    } 

有关详细说明,请参阅此question

答案 1 :(得分:0)

请尝试以下代码:

$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}')");
}

答案 2 :(得分:0)

我建议你追加

PHP_EOL 

PHP_EOL - 是PHP中的行尾常量,在字符串的末尾添加,而不是&#39; \ n&#39;

我希望它能解决问题,