hari dran
hari dran

Reputation: 115

Record is not added in to the database codeigniter 4

i am a begineer of codeigniter 4.i had a problem is Record is not added in to the database. i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops! We seem to have hit a snag. Please try again later... . i don't know how to solve problem what i tried so far i attached below.

View User.php

 <form method="post" id="add_create" name="add_create" action="<?php echo site_url('usersCreate');?>">
                       <div class="form-group col-md-6"> 
                           <label>First Name</label>
                                <input type="text" name="empid" class="form-control" id="fname" placeholder="fname">
                        </div>
                        <div class="form-group col-md-6"> 
                           <label>Last Name</label>
                                <input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
                        </div>

                      <div class="form-group col-md-6" align="center"> 

                        <Button class="btn btn-success" style="width: 80px;">Submit</Button>
              
                        </div>
                     
                 </form>

Controller User.php

    public function index()
    {
        return view('User');
    }

// insert data
public function store() {
    $userModel = new UserModel();
    $data = [
        'fname' => $this->request->getVar('fname'),
        'lname'  => $this->request->getVar('lname'),
    ];
    $userModel->insert($data);
    return $this->response->redirect(site_url('users'));
}

UserModel

<?php 
namespace App\Models;


class UserModel extends Model
{
    protected $table = 'records';

    protected $primaryKey = 'id';
    
    protected $allowedFields = ['fname', 'lname'];
}

Routes

$routes->get('/', 'User::index');

$routes->post('usersCreate', 'User::store');

Upvotes: 0

Views: 2025

Answers (2)

Chibueze Agwu
Chibueze Agwu

Reputation: 1000

I normally use a short method to get data and then submit it to the database. Here is what id do. check this. I am just updating your code


// insert data
public function store() {
    $userModel = new \App\Models\UserModel();
    $data = [
        'fname' => $this->request->getPost('fname'),
        'lname'  => $this->request->getPost('lname'),
    ];
    $userModel->insert($data);
    return redirect()->to(site_url('users'));
}

then check you html file you are missing the firstname name Try this one


 <form method="post" id="add_create" action="<?php echo site_url('usersCreate');?>">
                       <div class="form-group col-md-6"> 
                           <label>First Name</label>
                                <input type="text" name="fname" class="form-control" id="fname" placeholder="fname">
                        </div>
                        <div class="form-group col-md-6"> 
                           <label>Last Name</label>
                                <input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
                        </div>

                      <div class="form-group col-md-6" align="center"> 

                        <button type="submit" class="btn btn-success" style="width: 80px;">Submit</button>
              
                        </div>
                     
                 </form>

For the check your model i think is not configured well check this one


namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = 'id';

    protected $returnType     = 'object';
    protected $useSoftDeletes = false;

    protected $allowedFields = ['fname', 'lname', 'email']; // did you add this side of the site model

    protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;
}

Check my code if it did not help you call my attentions okay. I am still ready to help

Upvotes: 0

Oliver Adria
Oliver Adria

Reputation: 1143

I don't know CodeIgniter per se, but you should figure out how to get more meaningful data. Is your environment set to development environment? Usually you will get more info than Whoops! We seem to have hit a snag. Please try again later... and get more details on the error.

But I see you're trying to go to the page, where you add a user. There's 2 ways to methods to reach that page, GET (this is when you just go to the page as usual) and POST (this is when you submit the form).

But the request data will only be available if you submit the form. Thus you have to differentiate between the 2 methods. In your Controller you need to do something like

if ($this->request->getMethod() === 'post') { ... }

which is when you submit the form.

Check out https://codeigniter.com/user_guide/tutorial/create_news_items.html which should have more info. Snippet

public function create()
{
    $model = new NewsModel();

    if ($this->request->getMethod() === 'post' && $this->validate([
            'title' => 'required|min_length[3]|max_length[255]',
            'body'  => 'required'
        ]))
    {
        $model->save([
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', TRUE),
            'body'  => $this->request->getPost('body'),
        ]);

        echo view('news/success');

    }
    else
    {
        echo view('templates/header', ['title' => 'Create a news item']);
        echo view('news/create');
        echo view('templates/footer');
    }
}

Upvotes: 1

Related Questions