Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php将多行插入mysql数据库的最佳方法是什么?_Php_Mysql - Fatal编程技术网

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

使用php将多行插入mysql数据库的最佳方法是什么?,php,mysql,Php,Mysql,下面的php代码从表单中获取结果并将其插入到表中 我必须使用这个表结构,其中每一行对应一个不同于表名的值 我已经写了下面的代码,但是很麻烦。 你能帮我找个更好的办法吗?谢谢你 $lists = $_POST['form']['lists'][0]; $first_name = $_POST['form']['first_name']; $last_name = $_POST['form']['last_name']; $idu = $db->insertid();

下面的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代码,烧掉它并重新开始。它充满了安全问题和不良做法的味道。

只是好奇-为什么setQuery和query被分为两个函数呢?我猜:感谢heaps提供了zerkms的答案!效果很好。我刚刚从另一个站点复制了代码。我如何将setQuery和query结合起来?我刚才问了当今最愚蠢的问题吗?嗯,哪些安全问题?@StackOverflowNewbie:XSS与数据库无关。显然直接插入数据库和$\u POST数据?如果要以这种方式将变量直接导入数据库,则需要对其进行转义和绑定。@Aleksey Korzun:在哪里可以看到直接插入??他用$db->getescape方法清理了数据,不是吗。你们有点错了,他需要要么转义,要么将变量绑定到一个准备好的语句中,因为我们都知道,若你们使用框架的转义方法,你们将永远不会被利用。在当前或未来的框架修订中不存在错误的可能性。中间人攻击不可能覆盖包中的该方法。我们还知道,如果您已经转义了$u POST数据,则不需要准备好的语句/讽刺