【问题标题】:Laravel get each of lines from textarea and insert into new row in databaseLaravel 从 textarea 获取每一行并插入数据库中的新行
【发布时间】:2017-06-15 17:05:16
【问题描述】:

我正在尝试从 textarea 获取每一行并插入数据库中的新行。因此,当我编写带有新刹车线 f.ex 的文本列表时:
测试1
测试2
测试3

我想将这些多行中的每一个插入到 MySql f.ex 中的新行中:
id kwName
1. 测试1
2. 测试2
3. 测试3

请帮帮我。

我的代码是:

刀片

<textarea rows="1" name="kwName" class="form-control" placeholder="Insert keywords list"></textarea>
<input type="submit" class="btn btn-primary" name="add_kw" value="save">

控制器

if ($request->has('add_kw')) {

                $this->validate($request,[
                  'kwName'=> 'required',
                ]);

                // create new data              

                $values = new keyword;

                $values->kwName = $request->kwName;
                $values->website_id = $id;
                $values->save();
}

【问题讨论】:

  • 插入时使用foreach循环
  • 你应该能够拆分\n上的文本区域。

标签: php mysql arrays laravel


【解决方案1】:

我想这会对你有所帮助::

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

这只是示例,请根据需要使用它。

【讨论】:

  • 它帮了我很多,但现在它在我写时复制记录 f.ex:test1 test2,在表中显示 test1 test2 下一行再次测试 test2。我不知道为什么
  • 请给出完整的例子
  • $text = $_POST['kwName']; $textAr = explode("\n", str_replace("\r", "", $text)); $textAr = array_filter($textAr, 'trim'); foreach ($textAr as $line) { // 创建新数据 $line = new keyword; $line->kwName = $request->kwName; $line->website_id = $id; $line->保存(); }
  • 你不想重复的字段。您可以将该字段添加为唯一字段。
  • 如果对您有帮助,请点赞并接受它以帮助他人。
猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
相关资源
最近更新 更多