Reply to Re: insert multiple records into one table (one form)

Your name:

Reply:


Posted by NC on 04/16/06 19:37

GJPeacock@gmail.com wrote:
>
> Thanks for the reply NC, the trouble is i don't want the field to be an
> array,

Then tell us a little more about your form, so we can give you advice
appropriate to your situation... Also, why don't you want the field to
be an array?

> i want each item that is selected to be inserted into a new row.

This is exactly what this piece of code does. It creates one record
for each selected item. Obviously, the data in the example are
incomplete (the ID of the article to which selected articles are
related is missing, which is probably what prompted Jerry Stuckle's
comment about it violating first normal form for relational databases),
but it was only meant to show you the sequence of steps... Well, let's
try it again, this time with more data...

Let's say you have a form:

<form method="POST" action="insert.php">
<input type="checkbox" name="id[]" value="32">Article #32<br>
<input type="checkbox" name="id[]" value="38">Article #38<br>
<input type="checkbox" name="id[]" value="45">Article #45<br>
<input type="checkbox" name="id[]" value="59">Article #59<br>
<input type="hidden" name="referer" value="123">
<!-- This is the ID of the "referring" article -->
<input type="Submit">
</form>

Then, let's assume the user checked articles #32 and #59. These
values will be available to insert.php as fields in $_POST['id'], which

in this case will be an array. So in insert.php you can write:

$ref = $_POST['referer'];
$query = 'INSERT INTO related_articles (id, referer) VALUES (' .
implode(", $ref), (", $_POST['id']) . ", $ref)";
$result = mysql_query($query)
or die('Could not execute INSERT query');

Here's the query that is going to be executed:

INSERT INTO related_articles (id, referer)
VALUES (32, 123), (59, 123);

This query will create two records in related_articles, one linking
article #32 to article #123, the other linking article #59 to article
#123.

The advantage over Jerry Stuckle's solution is that all necessary
records are created in one query, although I must admit that this
advantage is probably trivial.

Cheers,
NC

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация