【问题标题】:Split multiple lines and input them in separate row in a database拆分多行并将它们输入到数据库中的单独行中
【发布时间】:2010-10-21 19:07:05
【问题描述】:

我正在尝试创建一个 php 脚本,该脚本将粘贴到 textarea 中的 HTTP 链接输入到数据库中的单独行中。更确切地说:

第一页是textarea(name=textarea-linkfield)所在的地方,链接会粘贴在这里

http://www.stackoverflow.com
http://www.yahoo.com
....
http://google.com

链接正在使用$linkfield=$_POST['textarea-linkfield']; 转移到php 脚本中,我希望将链接插入到数据库中,每行每个http 链接。数据库名:站点,表名犁,列:id,url,...

L.E.我尝试了作为概念证明:

$linkfield=$_POST['textarea-linkfield'];
$strip=explode("\n",$linkfield);
echo $strip[1];

但我收到 500 内部服务器错误

L.E.2

答案:

// Split the string into pieces
$pieces = explode("\n", str_replace(array("\n", "\r\n"), "\n", trim($linkfield)));

// Build the top of the INSERT query
$sql = "INSERT INTO `plow`(`url`) VALUES\n";

// Build the rest of the ;INSERT query by re-assembling the
// pieces.
$sql .= "('";
$sql .= implode("'), ('", $pieces);
$sql .= "')"; 
mysql_query($sql) or die ('Error: ' . mysql_error());

mysql_close();

感谢大家的帮助。 克里斯。

【问题讨论】:

  • "\n" 上的 explode() 应该可以工作,尝试一下,如果不成功,请尽最大努力返回一些代码。
  • 我更新了问题。谢谢,克里斯。
  • 您提交的表单中是否包含文本区域?
  • 看看 PHP 的错误报告功能,看看是否可以从错误中挤出更多信息:php.net/manual/en/function.error-reporting.php
  • 是的。常规形式,没什么花哨的。

标签: php mysql insert rows


【解决方案1】:

根据您的操作系统,换行符可以是“\n”、“\r\n”或“\r”。

试一试:

$strip=explode("<br>", nl2br($linkfield));

或者更安全:

$strip=explode("\n", str_replace(array("\n", "\r\n"), "\n", $linkfield));

【讨论】:

  • Linux 环境,正在使用第二行代码,现在我需要拿出代码将其插入数据库。谢谢 PMV。
  • foreach ($strip as $website) { mysql_query("INSERT INTO table (url) VALUES ('$website')"); }
  • 感谢 PMV。像魅力一样工作。
【解决方案2】:

使用 preg_match 查找每个 URL 并将其添加到数据库中。 此页面上的示例 3 应该可以解决问题:http://php.net/manual/en/function.preg-match.php 这样您就可以输入 URL,而无需使用新行。 如果您只使用 URL,那么您还可以在每个 URL 之后添加一个分隔符,即一个逗号(不在 URL 中使用),以使用评论中的 explode() 想法来分解它们。

【讨论】:

  • 我想提出一个脚本,它可以在我不添加逗号或任何其他分隔符的情况下工作,并且需要将链接输入到 textarea 到一个新行中。谢谢,克里斯。
【解决方案3】:

【讨论】:

  • 谢谢特德,这确实是答案。我将答案粘贴在问题的底部供其他人使用。感谢你的帮助。晚安,克里斯。
猜你喜欢
  • 2019-10-25
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 2020-05-08
  • 2017-03-14
相关资源
最近更新 更多