简体   繁体   English

记录未添加到数据库中 codeigniter 4

[英]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.我是 codeigniter 4 的初学者。我有一个问题是记录未添加到数据库中。 i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops!我得到了这样的 url 链接 http://localhost:8080/index.php/usersCreate 错误说哎呀! 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查看用户.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控制器用户.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');

I don't know CodeIgniter per se, but you should figure out how to get more meaningful data.我不知道 CodeIgniter 本身,但你应该弄清楚如何获得更有意义的数据。 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...通常你会得到比Whoops! We seem to have hit a snag. Please try again later...更多的信息Whoops! We seem to have hit a snag. Please try again later... Whoops! We seem to have hit a snag. Please try again later... Whoops! We seem to have hit a snag. Please try again later... and get more details on the error. Whoops! We seem to have hit a snag. Please try again later...并获取有关错误的更多详细信息。

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).有两种方法可以访问该页面, GET (这是您像往常一样进入该页面时)和POST (这是您提交表单时)。

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.查看https://codeigniter.com/user_guide/tutorial/create_news_items.html应该有更多信息。 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');
    }
}

I normally use a short method to get data and then submit it to the database.我通常使用一种简短的方法来获取数据,然后将其提交到数据库。 Here is what id do.这是 id 的作用。 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然后检查你的 html 文件你是否缺少名字 试试这个


 <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我仍然准备提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM