我有一个简单的表单,它是一个文本区域,我需要将文本区域中的每一行插入到 MySQL 中的不同行中。
HTML代码:
<html>
<form method="POST" action="insert.php">
<textarea name="url" rows="10" ></textarea>
<input type="submit" name="submit" value="Enter">
</form>
</html>
PHP 代码:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('insert', $link);
if (!$db_selected) {
die ('Can\'t use this database : ' . mysql_error());
}
$textarea = mysql_real_escape_string($_POST['url']);
$array = explode("\n", $textarea);
$i=0;
$value = trim($array[$i]);
if (!empty($value)) {
foreach ($array as $value) {
mysql_query("INSERT INTO test (text) VALUES ('{$array[$i]}')") or die(mysql_error());
$i++;
}
}
mysql_close($link);
?>
目前,当我提交表单时,我会将文本区域存储在一行中。你能帮我解决这个问题吗?
最佳答案
试试这个:
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r chars
foreach ($textAr as $line) {
// Your sql Query here with $line as the string.
}
关于php - MySQL从文本区域插入到多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37711880/