【问题标题】:PHP split the content of text area and insert into mysqlPHP分割文本区内容并插入mysql
【发布时间】:2012-01-12 11:17:09
【问题描述】:

我需要知道如何使用 php 编码执行以下操作

  1. 从文本区域获取插入的文本
  2. 按行拆分内容
  3. 将每一行作为自己的行插入到数据库中,并带有自己的 ID 号

谁能告诉我怎么做?

谢谢

EDIT________

这是我迄今为止尝试过的

$is_first = true;


foreach (explode('\n', $_POST['code']) as &$voucher) {

    if ($is_first) $is_first = false; else $query .= ', ';

    $query .= '(' . mysql_real_escape($voucher) . ')';
    mysql_query('INSERT INTO back_codes (`code_id`, `code`) VALUES (NULL, "$voucher")');
}

【问题讨论】:

  • 具体是什么问题?到目前为止,您尝试过什么?
  • 已经编辑了迄今为止尝试过的主要字段

标签: php mysql textarea


【解决方案1】:
  1. 使用$_POST['field_name']引用它,如果它是通过POST请求发送的,像这样:

    $textarea_value = $_POST['my_textarea'];
    
  2. 您可以使用explode() 拆分字符串,如下所示:

    $lines = explode("\n", $textarea_value);
    
  3. 遍历explode() 的结果,然后将行一一插入到数据库中。

    foreach ($lines as $line) {
        // $line here is a string
        // build a query based on it and execute it
    };
    

【讨论】:

  • @meohmy:我很高兴它有帮助:)
【解决方案2】:

我希望您通过提交 POST 表单数据从 textarea 发送数据。 假设您的 textarea 看起来像这样:

<textarea name="data"></textarea>

然后在 PHP 中你可以使用以下代码:

if(isset($_POST["data"]))
{
  $line_data = explode("\n", $_POST["data"]);
  foreach($line_data as $key => $value)
{
  $sql = "INSERT INTO table (col) VALUE('{$value}')";
 mysql_query($sql);
}
}

【讨论】:

    最近更新 更多