0

I've got a home-grown LAMP app that uses the same HTML code for the "Modify record" and "New record" pages based on whether it is passed a blank record or a non-blank record. Currently, I'm creating the blank record by selecting a single record from the MySQL table and manually setting each field (by name) to NULL. There's got to be a better way to do this, but the search terms to find what I need are just too darn generic. I've looked at using something like mysql_fetch_array or get_class_vars, but I just can't get them to work. Here's what I'm trying to replace with something a bit less manual:

// Select a row, any row... (using CodeIgniter)
$q = $this->db->get($this->config->item('db'),1);
// For each ... um ... one ... row, add it to $data
foreach ($q->result() as $row) {
    $data[] = $row;
}
// set each **KNOWN** field to NULL
$data[0]->column1 = NULL;
$data[0]->column2 = NULL;
...

I know it's a dirty hack, but it works. What's the "right" way to do this?

4

2 回答 2

1

我相信你正在这样做:

$data[0] = (object) array_fill_keys($this->db->list_fields('your_table_name'), null);

参考:CI->db->list_fields()array_fill_keys()类型转换

于 2013-09-22T17:16:09.673 回答
0

如果你只得到 1 行,你最好使用 ->row() 方法而不是 resuls() 和无用的 foreach 循环

例如:

$row = $this->db->select('*')->from('table')->get()->row();

现在解决您的问题,您必须定义您正在使用的字段

$fields = array('id', 'name', '...etc');

那么如果不可用,你会做这样的事情来变空

foreach ( $fields as $f ) $data[$f] = isset($row->$f) ? $row->$f : NULL;

这将使您的 $data 中的所有字段都可用,因此您可以将其传递给视图。

于 2013-09-22T13:33:08.113 回答