Reputation: 15
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?
Upvotes: 0
Views: 462
Reputation: 696
I believe you are doing exactly this:
$data[0] = (object) array_fill_keys($this->db->list_fields('your_table_name'), null);
Reference: CI->db->list_fields(), array_fill_keys(), type casting
Upvotes: 1
Reputation: 2729
If you're getting 1 row only, you'd better off using ->row() method instead of a resuls() & useless foreach loop
e.g:
$row = $this->db->select('*')->from('table')->get()->row();
getting to your problem now, you'll have to define the fields you're using something like this
$fields = array('id', 'name', '...etc');
then you'll do something like this to get empty if not available
foreach ( $fields as $f ) $data[$f] = isset($row->$f) ? $row->$f : NULL;
this will make all fields available in your $data, so you can pass it to a view.
Upvotes: 0