You are here: Re: form post to database best practice? « PHP Programming Language « IT news, forums, messages
Re: form post to database best practice?

Posted by Steve on 04/23/07 18:24

<Muchach@gmail.com> wrote in message
news:1177351146.931339.322320@b75g2000hsg.googlegroups.com...
| Hello,
| Ok so what I've got going on is a form that is populated by pulling
| info from database then using php do{} to create elements in form. I
| have a text box in each table row for the user to enter input. I need
| to take this user input and put it back into the database. What would
| be the best method to do this. I can't use a normal post because the
| name of the text box is the same for each table row. I've heard that
| posting the variables into the URL is not a good idea if they are
| going to be inserted into the database. So what is the best method
| here?

getting (form method=get) is no more or less safe than posting (via form
method=post)...whomever gave you that advice ain't the best resource for
you.

i assume you're presenting this like a grid? if so, you can name all of your
inputs with the same name and end them with [].

here's some sample code for you...imagine a manufacturer who has to define
part with a code, description, etc..

forgive, and fix, the text wrapping to test.

<?
$cells = isset($_REQUEST['cells']) ? $_REQUEST['cells'] : array();
$dealerName = getDealerName($dealer); // just hard code something here.
$pageTitle .= ' - ' . $dealerName . ' - ' . $dealer;

$save = isset($_REQUEST['save']);

$columns = array(
'CODE' ,
'DESCRIPTION' ,
'CATEGORY'
);
$columnCount = count($columns);
$errors = array();
$categories = array(
'BODY' ,
'FRAME' ,
'MECHANICAL' ,
'PAINT'
);
if (!is_array($cells)){ $cells = array($cells); }

function formatCells(&$value)
{
$value = strtoupper($value);
}

function isValid($columns, $column, $value, $categories, &$error)
{
$error = '';
switch ($column)
{
case 'CODE' : if (!empty($value))
{
$length = strlen($value);
if ($length > 40)
{
$error = $column . ' 40 character limit';
return false;
}
return true;
}
$error = $column . ' required';
break;
case 'DESCRIPTION' : if (!empty($value))
{
$length = strlen($value);
if ($length > 255)
{
$error = $column . ' 255 character limit';
return false;
}
return true;
}
$error = $column . ' required';
break;
case 'CATEGORY' : if (in_array($value, $categories)){ return true; }
$error = $column . (empty($value) ? ' required' :
$value . ' not an option');
break;
}
return false;
}

// format inputs
array_walk($cells, 'formatCells');
// tag errors for submitted data
$errors = array();
$records = array();
$recordCount = count($cells) / count($columns);
foreach ($cells as $index => $value)
{
$column = $columns[$index % $columnCount];
$row = floor($index / $columnCount);
$records[$row][$column] = $value;
if ($errors[$row][$column]){ continue; }
$isValid = isValid($columns, $column, $value, $categories, $error);
if (!$isValid) { $errors[$row][$column] = $error; }
if ($column != 0){ continue; }
// enforce unique index on code column
for ($record = $row + 1; $record < $recordCount; $record++)
{
$cell = $record * $columnCount;
if ($value != $cells[$cell]){ continue; }
$errors[$record]['CODE'] = 'Duplicate code';
}
}
ksort($errors);
?>
<style type="text/css">
.symLink
{
color : navy;
cursor : pointer;
font-size : 7.25pt;
text-align : right;
text-transform : none;
}
input ,
select ,
td
{
font-size : 8pt;
text-align : left;
text-transform : uppercase;
}
</style>
<script type="text/javascript">
function saveGrid(remove)
{
if (remove)
{
if (!confirm('Are you sure you want to delete this record?')){
return; }
var current = window.event.srcElement;
while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.removeChild(current);
}
records.submit();
}
</script>
<br>
<br>
<div class="bullet" style="background:white no-repeat url('<?=
site::$imagesDirectory ?>bullet.jpg'); color:black; font-size:8pt;
height:50px; padding-top:8px; padding-left:50px;">
<?= $pageTitle ?>
</div>
<hr>
<br>
<br>
<div style="background-color:#EEEEBB; border:1px solid steelblue;
font-size:8pt; font-weight:600; margin-right:15px; padding:10px;">
Please make sure you save your work when you have finished editing.
<br>
Failure to do so will result in the loss of your efforts.
</div>
<br>
<hr>
<br>
<form name="records" method='post'>
<table id="grid" style="width:600px;">
<?
function buildOptionList($value, $key, &$options)
{
$options[1][] = '<option value="' . $value . '" ' .
($value == $options[0] ? 'selected' : '') .
'>' . $value . '</option>';
}

echo " <th>&nbsp;</th>\r\n";
foreach ($columns as $column)
{
?>
<th><?= $column ?></th>
<?
}
echo "\r\n" . '<tr><td colspan="4"><hr></td></tr>' . "\r\n";
echo "\r\n<tr>\r\n";
echo '<td><span class="symLink" title="Add"
onclick="saveGrid();">Add</span></td>' . "\r\n";
echo '<td><input name="cells[]" style="width:200px;" maxlength="40"
type="text" value="" autocomplete="off"></td>' . "\r\n";
echo '<td><input name="cells[]" style="width:300px;" maxlength="255"
type="text" value="" autocomplete="off"></td>' . "\r\n";

$options = array();
$optionList = array('', &$options);
array_walk($categories, 'buildOptionList', $optionList);

echo '<td><select name="cells[]" style="width:200px;">' . "\r\n";
echo implode("\r\n", $optionList[1]);
echo '</select></td>' . "\r\n";
echo "\r\n</tr>\r\n";

// db::execute and other db calls
// are part of an abstract class not shown here
// just call your db's built in equivalent in php

if ($save)
{
$sql = "
DELETE
FROM roLaborCodes
WHERE Dealer = '" . $dealer . "'
";
db::execute($sql);
} else {
$sql = "
SELECT Code ,
Description ,
Category
FROM roLaborCodes
WHERE Dealer = '" . $dealer . "'
ORDER BY Stamp DESC
";
$records = db::execute($sql);
}
if ($records){ echo "\r\n" . '<tr><td colspan="4"><hr></td></tr>' .
"\r\n"; }
foreach ($records as $row => $record)
{
if (count($errors[$row])){ continue; }
if ($save)
{
$values = $record;
//prepararray simply double ticks single ticks
// so that the insert works on, like, 'foo's got bar'
array_walk($values, 'prepareArray');
$sql = "
INSERT INTO roLaborCodes
(
Dealer ,
" . implode(",\r\n ", $columns) . "
)
VALUES
(
'" . user::$dealership . "' ,
'" . implode("',\r\n '", $values) . "'
)
";
db::execute($sql);
}
echo "\r\n<tr>\r\n";
echo '<td><span class="symLink" title="Delete"
onclick="saveGrid(true);">Delete</span></td>' . "\r\n";
foreach ($columns as $column)
{
$input = '';
switch ($column)
{
case 'CATEGORY' : $options = array();
$optionList = array($record[$column], &$options);
array_walk($categories, 'buildOptionList',
$optionList);
$optionList = implode("\r\n", $optionList[1]);
$input = '<select name="cells[]"
style="width:200px;">' . "\r\n";
$input .= $optionList;
$input .= "</select>\r\n";
break;
default : $maxLength = $column == 'CODE' ? 40 : 255;
$width = $column == 'CODE' ? '200px' : '300px';
$input = '<input name="cells[]" style="width:'
.. $width . ';" maxlength="' . $maxLength . '" type="text" value="' .
$record[$column] . '" autocomplete="off">';
break;
}
echo ' <td>' . $input . "</td>\r\n";
}
echo "\r\n</tr>\r\n";
}
if (count($errors) > 1 || ($errors && count($errors[0]) != 2))
{
echo "\r\n" . '<tr><td colspan="4"><hr></td></tr>' . "\r\n";
echo "\r\n" . '<tr><td colspan="4" style="background-color:#FF9999;
border:1px solid steelblue; font-weight:bold; padding-bottom:10px;
padding-top:10px;">ERROR: COULD NOT UPDATE</td></tr>' . "\r\n";
foreach ($records as $row => $record)
{
if (!count($errors[$row])){ continue; }
if ($row == 0 && count($errors[$row]) > 1){ continue; }
echo "\r\n<tr>\r\n";
echo '<td>&nbsp</td>' . "\r\n";
foreach ($columns as $column)
{
$error = $errors[$row][$column];
$color = $error ? '#FF9999' : 'white';
$title = $error ? $error : '';
$value = $record[$column] ? $record[$column] : $error;
echo ' <td style="cursor:pointer;" title="' . $title . '">' . $value
.. "</td>\r\n";
}
echo "\r\n</tr>\r\n";
}
}
echo "\r\n" . '<tr><td colspan="4"><hr></td></tr>' . "\r\n";
?>
</table>
<br>
<br>
<input name="save" type="hidden" value="1">
<input type="submit" value="Save ..." style="font-size:10pt;
text-align:center; text-transform:none;">
</form>

 

Navigation:

[Reply to this 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

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