Reputation: 31
here is my site_model code get all data from database and insert data into database using Html form please help i don't know where i do mistake
class Site_model extends CI_Model
{
public function __construct()
{
}
// get all data from database
public function get_records()
{
$query = $this->db->get('user_data');
return $query->result();
}
// add records into database by form
public function add_record($formData)
{
$this->db->insert('user_data', $formData);
}
}
than i load model into controller and get values in an array. and after create an array to send form values into database
class Site extends CI_Controller
{
var $data = array();
public function __construct()
{
parent::__construct();
$this->load->model('Site_model');
}
public function index()
{
//get data into array from model
$data = $this->data;
$data['user_info'] = $this->Site_model->get_records();
// get data from html form and send to database
$formData = array(
'title' => $this->input->post('post_title'),
'description' => $this->input->post('post_descrip')
);
// send record to model
$this->Site_model->add_record($formData);
$this->load->view('crud_viw', $data);
}
}
my view code look like this
<!DOCTYPE html>
<html>
<head>
<title>Crud</title>
</head>
<body>
// Html form to send values to database
<form method="post">
<input type="text" placeholder="Title" name="post_title"></input>
<input type="text" placeholder="Description" name="post_descrip"> </input>
<button type="submit">Submit</button>
</from>
</body>
</html>
Upvotes: 0
Views: 2745
Reputation: 6994
The simple way to prevent getting the a database error occurred column 'title' cannot be null
is use ternary operator(?:)
.If you have not posted value it will inserts empty string.
$formData = array(
'title' => isset($this->input->post('post_title'))?$this->input->post('post_title'):" ",
'description' => isset($this->input->post('post_descrip'))?$this->input->post('post_descrip'):" "
);
Hope it works.
Upvotes: 0
Reputation: 200
in your database your column "title" should be not null..so mark "title" as not null in database.. Hope it helps..
Upvotes: 0
Reputation: 16436
Change your index method as below. You only have to enter data when post event occur
public function index()
{
//get data into array from model
$data = $this->data;
$data['user_info'] = $this->Site_model->get_records();
if($this->input->post()){ //<--- add this condition
// get data from html form and send to database
$formData = array(
'title' => $this->input->post('post_title'),
'description' => $this->input->post('post_descrip')
);
// send record to model
$this->Site_model->add_record($formData);
}
$this->load->view('crud_viw', $data);
}
Upvotes: 2