Tag Archives: elegant solution

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!

PHP: The Array Element Doesn’t Exist – Suppress the Warnings

What’s the problem?

If you code PHP from couple of hours you are probably familiar with the following problem:

1
2
3
4
5
6
7
8
9
<?php
 
	error_reporting(E_ALL);
 
	$arr = array();
 
	echo $arr[3];
 
?>

The first and most common solution is just by adding the isset() statement and the code will look like that:

1
2
3
4
5
6
7
8
9
10
<?php
 
	error_reporting(E_ALL);
 
	$arr = array();
 
        if (isset($arr[3]))
	        echo $arr[3];
 
?>

However do you know there’s is another simple and elegant solution? Simply add the @ sign to suppress the element existence

1
2
3
4
5
6
7
8
9
<?php
 
	error_reporting(E_ALL);
 
	$arr = array();
 
	echo @$arr[3];
 
?>