Barlet Barlet - 4 months ago 37
PHP Question

PHP Codeigniter insert delete update with submit buttons

Need help with PHP Codeigniter framework.

I have a form with 3 Submit buttons. I want to Insert - Update - Delete using those buttons. I successfully made the Insert button work. So when I click on Insert the data is stored in MySQL Database table. Since they are all submit buttons all of them are doing the same action.

when I change type input type="button" is not working.

below is my php code.

Model

class Users_model extends CI_Model

{

function get_All_Users(){

$query = $this->db->get('users');
if($query->num_rows() > 0){
foreach($query->result() as $row) {
$data[]=$row;
}
}
return $data;
}


function insert_users($data){
$query = $this->db->insert('users', $data);
return;


}

function update_users($data){
// update code...
}
}


Controller

public function add_users(){

$this->load->view('users_view');
}

public function create_users(){

$username = $this->input->post('username');
$password = $this->input->post('password');


$data = array(
'username' => $username,
'password' => $password,
);

$this->load->model('user_model');
$this->users_model->insert_users($data);
$this->load->view('users_view');
redirect('users', 'refresh');

}


View

<form role="form" action="<?php echo base_url().'index.php/users/create_users'?>" method="post">
<table class="table">
<thead>

</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<label for="Username">Username</label>
<input type="textbox" id="username" name="username">
</div>
</td>

<td>
<div class="form-group">
<label for="Password">Password</label>
<input type="textbox" id="password" name="password">
</div>
</td>
</tr>

<tr>
<td>
<input type="submit" value="Insert" />
<input type="submit" value="Update" />
<input type="submit" value="Delete" />
</td>
</tr>
</tbody>
</table>

</form>


So I want when I click on update button to run function update!

Answer

Firstly give names to buttons

<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />

and try the following function

public function create_users(){
    $this->load->model('user_model');
if($this->input->post('insert') != ''){
/*Perform insert operation here*/

    $username = $this->input->post('username');
    $password = $this->input->post('password');


    $data = array(
        'username' => $username,
        'password' => $password,
    );


    $this->users_model->insert_users($data);
}
else if($this->input->post('update') != ''){
     /*perform update operation here*/
}
else if($this->input->post('delete') != ''){
     /*perform delete operation here*/
}
    $this->load->view('users_view');
    redirect('users', 'refresh');

}
Comments