What's the best way to insert multiple rows into a mysql database using php?
The php code below get's the results from a form and inserts them into a table.
I have to used this table structure where each row corresponds to a different value from the form eg First Name.
I've written the code below but it's cumbersome. Can you help me with a better way? Thanks heaps!
$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`) VA开发者_JS百科LUES ('" . $db->getEscaped($lists) . "', 'Last Name'
, '" . $db->getEscaped($last_name) . "', '" . $db->getEscaped($idu) . "')");
$db->query();
You can perform bulk insert:
INSERT INTO table (field1, field2) VALUES ('val1', 'val2'), ('val3', 'val4'), ...
In your case it is something like:
$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)."')");
To answer your SQL question:
INSERT INTO `table` (foo, bar)
VALUES (1, 2),
(3, 4),
(5, 6),
(7, 8)
In regards to your PHP code, burn it and start over. It reeks of security issues and bad practices.
精彩评论