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?

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

Which basically works like this:

    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);
    $q = $this->db->get('users');

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

    return FALSE;

And in your controller:

public function index($id)
    $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;
    echo ''; # default value

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.