0

Hi, I am a new web developer. I am now doing with PHP MVC (CodeIgnitor). Could anyone give me the example of how to get data from database to form, then save back to database?

2
Contributors
1
Reply
16
Views
2 Years
Discussion Span
Last Post by cereal
0

Hi, you have to use set_value() from the Form helper:

Which basically works like this:

<input
    type="text"
    name="first_name"
    value="<?php echo set_value('first_name', 'default value'); ?>"
    />

Where the first argument is the value assumend by the form after a submission, so in case of POST data it will repopulate with the latest data. The second argument is the default value, this is optional, BUT this is where you set your database values, by applying a ternary operator:

As example the above PHP code changes to:

<?php echo set_value('first_name', ($row ? $row->first_name : '')); ?>

Where $row is the object (or the array) returning the value from the database, i.e. in your model you set something like this:

public function get_user($id)
{
    $this->db->where('user_id', $id);
    $this->db->limit(1);
    $q = $this->db->get('users');

    if($q->num_rows() > 0)
        return $q->row();

    return FALSE;
}

And in your controller:

public function index($id)
{
    $this->load->model('users');
    $data['row'] = $this->users->get_user($id);

    $this->load->view('view', $data);
}

In my example:

$row ? $row->first_name : ''

works because in the model I set boolean FALSE when the database returns 0, and the implicit condition is like writing:

if($row !== FALSE)
    echo $row->first_name;
else
    echo ''; # default value

but you can change the condition to check if it is an object or an array. It's up to you.

Edited by cereal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.