CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE
Need a Website Or Web Application.Contact : +91 9437911966 (Whatsapp) Note: Paid Service

How to Insert data using Codeigniter 4


view

<div class="register-box">
<?= \Config\Services::validation()->listErrors(); ?>
<?= \Config\Services::session()->getFlashdata('msg'); ?>
<form method="post" action="<?= base_url() ?>/Contact/save">
	<div class="form-group">
		<label for="name">Name:</label>
		<input type="text" name="name" class="form-control" placeholder="Enter Name" id="name">
	</div>
	<div class="form-group">
		<label for="age">Age:</label>
		<input type="number" name="age" class="form-control" placeholder="Enter Age" id="age">
	</div>
	<div class="form-group">
		<label for="email">Email address:</label>
		<input type="email" name="email" class="form-control" placeholder="Enter email" id="email">
	</div>
	<button type="submit" class="btn btn-primary">Submit</button>
</form>

</div>

controller

<?php namespace App\Controllers;

use CodeIgniter\Controller;
class Contact extends BaseController
{
	public function __construct(){
    }
	public function index()
	{
		$data['title']   = "Contact";
		return view('contact',$data);
	}
	public function save(){
		$data = $this->request->getVar();
		$validation =  \Config\Services::validation();
		$validation->setRules([
			'name' => 'required|string',
			'age' => 'required|integer|greater_than[0]',
			'email' => 'required|valid_email'
		]);
		$res = $validation->withRequest($this->request)
			->run();
		if(!$res){
		
			$data['title'] = "Contact";
			echo view('contact',$data, [
					'validation' => $validation
			]);
		}
		else{
			$contactModel = new \App\Models\ContactModel();
			$session = \Config\Services::session();
			try{
				$contactModel->insert($data);
				$session->setFlashdata('msg', 'Record Inserted successfully');
			}
			catch(\Exception $e){
				$session->setFlashdata('msg', 'Something went wrong');
			}
			$data['title'] = "Contact";
			echo view('contact',$data);
		}
	}



}


Models

<?php namespace App\Models;

use CodeIgniter\Model;

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

    protected $returnType     = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['name', 'age', 'email'];

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

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