【发布时间】:2014-12-17 04:11:45
【问题描述】:
我有一个 HTML 表单。 我有一个 MySQL 表。
表单具有名称属性,例如“last_name”、“first_name”、“unique_id”等。
MySQL 数据库表的列名称为“last”、“first”、“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 变量数组。
- 我不知道他们每次表格时会订购什么 提交。
- 我不知道哪些表单元素会一直是 提交。
- 我不想将表单属性的名称作为数据库的列名。
- 我不确定是否将我在 MySQL 中的查询更改为使用别名。为了 例如,使用 LAST 作为“last_name”。
- 我真的不想更改数据库架构,因为我想要这样 “几乎”与数据库无关。
有没有比我做的更好的方法?
这是我更新数据库的代码:
$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 ?>"/>
谢谢。
【问题讨论】:
-
基本上你想构建一个查询为“插入表(”然后循环遍历每个列名“)值(”然后循环遍历每个值名称“)”只要你保持顺序,并拥有所需的一切(例如,不为空)然后你就可以了
-
@MarshallTigerus 如果我不能保持订单怎么办?我只知道测试该值是否已设置。
-
你应该能够保持列和值相互匹配,否则顺序无关紧要。