Is there a better way to process a form where I need to save a link and link text against a language and company?
The example below works, but I think it is hard work.
I have added the language and company id to the key of the link and link text fields as a way of grouping them together and passing the other information through to PHP and into the DB.
$newlinks = array();
foreach($_POST as $post_key => $post_value) {
if (substr($post_key, 0, 7) == 'newlink') {
$posted_link = explode('_', $post_key);
$newlinks[$posted_link[1]][$posted_link[2]][$posted_link[0]] = $post_value;
$newlinks[$posted_link[1]][$posted_link[2]]['language_id'] = $posted_link[1];
$newlinks[$posted_link[1]][$posted_link[2]]['company_id'] = $posted_link[2];
}
}
foreach($newlinks as $newlinklang) {
foreach($newlinklang as $newlink) {
if ($newlink['newlink'] != '' && $newlink['newlinkname'] != '') {
$sql = "
INSERT
INTO
".$db_prefix."catalogue_links (
link,
link_name,
language_id,
company_id
) VALUES (
'".$newlink['newlink']."',
'".$newlink['newlinkname']."',
'".$newlink['language_id']."',
'".$newlink['company_id']."'
";
}
}
}
And the HTML
<input type="text" name="newlink_1_1" value="" />
<input type="text" name="newlinkname_1_1" value="" />
There can be multiple languages and companies displayed on one page.
Use
something[]as the field name. Then PHP will create an array in$_POST['something'](or $_GET, and $_REQUEST – obviously) which you can use without ugly substring comparisons.You could also specify array indexes in the field name (
name="something[42]"). This might be a good idea if you have multiple fields which belong together. While the order is supposed to be correct anyway (so you canforeach($_POST['field1'] as $idx => $val)and use_POST['field2'][$idx]) it might be safer or at least more intuitive for someone reading the code if the indexes are also in the HTML code.