One Form – Multiple DB Records

I’ve the impression that even it’s a simple technique it remains quite misunderstood!

What’s the Goal?

You’ve a simple HTML form with several groups of form elements. Imagine the situation with title and link groups. You can have 1, 2 or more title/link pairs which you’d like to save in a database table, where perhaps there are only three columns – id, title, link.

What is the Shortest Path to the Solution?

In fact the task can be done by many ways, but there’s one really elegant solution. As it appears in many occasions PHP and HTML are born to work together!

1. First Step

Create your web form by simply modifying a bit the element names. Usually when you have an input you simply name it after the database column or something similar.

<form method="POST">
	<input type="text" name="db_column_name" />
</form>

In reality PHP and HTML allows the name to be an array element, just like so:

<form method="POST">
	<input type="text" name="link[0][title]" />
	<input type="text" name="link[0][url]" />
 
	<input type="text" name="link[1][title]" />
	<input type="text" name="link[1][url]" />
</form>

2. Second Step

Than all this comes in the _POST array in PHP, but formatted in an array manner, so you can simply foreach it!

<?php
 
foreach ($_POST['link'] as $link) {
	insert_into_db($link['title'], $link['url']);
}
 
?>

That is simply enough!

Related posts:

  1. Secure Forms with Zend Framework
  2. How to Sanitize User Input in PHP?
  3. Automatically Upload Images with PHP Directly from the URI
This entry was posted in PHP, web development and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">