php - Unable to get, insert data from Database with codeigniter 4
I am trying the new codeigniter 4 Trying to create first app following tutorial https://codeigniter.com/user_guide/tutorial/news_section.html
My controller method to insert data
public function create()
{
$model = new NewsModel();
if (! $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
])) {
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
} else {
$model->save([
'title' => $this->request->getVar('title'),
'slug' => url_title($this->request->getVar('title'), '-', true),
'body' => $this->request->getVar('body'),
]);
echo view('news/success');
}
}
It is echoing success page but data not inserting into database.
In .env file I used
database.default.hostname = localhost
database.default.database = news_db
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
I think db connection working as checked with wrong database details its not working
My model is
<?php namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
protected $table = 'news';
protected $allowedFields = ['title', 'slug', 'body'];
public function getNews($slug = false)
{
if ($slug === false) {
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
Answer
Solution:
The error is most likely coming from your Model declaration in the Controller.
$model = new NewsModel();
It should be namespaced.
Try:
$model = new \App\Models\NewsModel();
or
$model = model('NewsModel');
Answer
Solution:
I am suggesting that: if you haven't you should follow the tutorial strictly by extending the core controller because you did not show that in your code.
use CodeIgniter\Controller;
class News extends Controller
And You didnt use App\Models\NewsModel; Before instantiating your Model class. You can only do that in the way Ali-coder illustrate. Again still suggesting you should have use
$request->getPost() Instead of $this->request->getVar('title') I am suggesting all this because that is how i wrote mine and it work fine.
Source