我有一个HTML表单。 我有一个MySQL表。
表单具有名称属性,例如" last_name," "如first_name," " UNIQUE_ID,"等
MySQL数据库表的列名为" last," "第一," " something_special_id,"等
我所做的是创建一个新数组并将其从表格列映射到表格列名称。然后我发回新数组,然后我可以更新我的数据库。
问题是我想让它变得动态。
我做到了:
if (isset($myArray['last_name']))
{
//Gets the current value of the form array sent in POST
//and puts that value into the new array which is labeled
//with the correct table column name;
//e.g. $myArray['last_name']= "Smith";
//now $mappedColumnNames['LAST'] is equal to "Smith";
$mappedColumnNames['LAST'] = $myArray['last_name'];
}
if (isset($myArray['first_name']))
{
$mappedColumnNames['FIRST'] = $myArray['first_name'];
}
if (isset($myArray['diploma']))
{
$mappedColumnNames['DIPLOMA'] = $myArray['diploma_value_from_form'];
}
if (isset($myArray['secret_number']))
{
$mappedColumnNames['SECRET'] = $myArray['secret_number_from_form'];
}
unset($myFormValues);
$mappedColumnNames
数组是数据库列名。 $myArray
数组是表单发送的POST变量数组。
有没有比我做的更好的方法呢?
以下是我更新数据库的代码:
$mappedColumnNames = parent::mapColumnNames($_student_search);
//What I use now but it won't work because the form names are not the column names.
foreach($_student_search as $key => $value)
{
//echo '</br>key: ' . $key . ', value: ' . $value . '</br>';
$columns[] = $key . ' = ?';
$new_value[$key] = $value;
}
//I don't need the text input button, which occurs first
array_shift($columns);
array_shift($new_value);
$sql = 'UPDATE students ';
$sql .= ' SET ' . implode(' AND ', $columns);
$sql .= ' WHERE student_id = ' . $new_value['student_id'];
$this->adapter->prepare($sql);
$this->adapter->execute($new_value);
编辑:
我最终接受了这些建议并做了:
public function getFormNameMapping()
{
$realColumnNames = parent::getColumnNames('students');
$realKeyNames = parent::getColumnNames('students');
return array_combine($realColumnNames, $realKeyNames);
}
protected function getColumnNames($myTable)
{
$sql = "DESCRIBE " . $myTable; //mysql only
$this->adapter->prepare($sql);
$this->adapter->execute();
$results = $this->adapter->fetchAll(PDO::FETCH_COLUMN);
return $results;
}
然后:
$student_model = $this->model->getStudentModel();
$student = $student_model->findByStudentID($studentID);
$mappedColumnNames = $student_model->getFormNameMapping();
<input name="<?PHP echo $mappedColumnNames['FIRST']; ?>" type="text" class="text" value="<?PHP echo $student->FIRST ?>"/>
感谢。
答案 0 :(得分:2)
可能是一个更好的方法来考虑,但对于这个问题:
$crossRef = array('FIRST'=>'first_name', 'LAST'=>'last_name'); //etc...
foreach($crossRef as $key => $val) {
if(!empty($myArray[$val])) {
$mappedColumnNames[$key] = $myArray[$val];
}
}
我从数据库中提取列名,然后使用列名创建表单。它将与DB无关,因为它基于DB列动态创建表单。