繁体   English   中英

使用 php 将多行插入 mysql 数据库的最佳方法是什么?

[英]What's the best way to insert multiple rows into a mysql database using php?

下面的 php 代码从表单中获取结果并将它们插入到表格中。

我必须使用这个表结构,其中每一行对应于表单中的不同值,例如名字。

我已经编写了下面的代码,但它很麻烦。 你能帮我一个更好的方法吗? 多谢!

$lists      = $_POST['form']['lists'][0];
$first_name = $_POST['form']['first_name'];
$last_name  = $_POST['form']['last_name'];
$idu        = $db->insertid();

$db->setQuery("INSERT INTO #__rsmail_subscriber_details (`IdList`, `FieldName`, 
`FieldValue`, `IdSubscriber`) VALUES ('" . $db->getEscaped($lists) . "', 'First Name'
, '" . $db->getEscaped($first_name) . "', '" . $db->getEscaped($idu) . "')");

$db->query();

$db->setQuery("INSERT INTO #__rsmail_subscriber_details (`IdList`, `FieldName`, 
`FieldValue`, `IdSubscriber`) VALUES ('" . $db->getEscaped($lists) . "', 'Last Name'
, '" . $db->getEscaped($last_name) . "', '" . $db->getEscaped($idu) . "')");

$db->query();

您可以执行批量插入:

INSERT INTO table (field1, field2) VALUES ('val1', 'val2'), ('val3', 'val4'), ...

在您的情况下,它类似于:

$db->setQuery("INSERT INTO #__rsmail_subscriber_details (`IdList`, `FieldName`, 
`FieldValue`, `IdSubscriber`) VALUES ('".$db->getEscaped($lists)."', 'First Name'
, '".$db->getEscaped($first_name)."', '".$db->getEscaped($idu)."'), ('".$db->getEscaped($lists)."', 'Last Name'
, '".$db->getEscaped($last_name)."', '".$db->getEscaped($idu)."')");

要回答您的 SQL 问题:

INSERT INTO `table` (foo, bar)
         VALUES (1, 2),
                (3, 4),
                (5, 6),
                (7, 8)

关于您的 PHP 代码,烧录它并重新开始。 它充满了安全问题和不良做法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM