I'm trying to make upload image function on Codeigniter. but, when I trying to insert the image to the database. the variable can't be detected.
Here is my controller :
public function registrasi() {
//VALIDATION
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tb_m_user.email]');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]|matches[konfirmasi_password]');
$this->form_validation->set_rules('konfirmasi_password', 'Retype Password', 'required|trim|matches[password]');
if($this->form_validation->run() == false) {
$this->session->set_flashdata('fail' , 'Registration Failed! Please Try Again');
$this->load->view('auth/registrasi');
}else{
//INSERT TO DATABASE
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
$pict = $_FILES['pict'];
//LIBRARY UPLOAD CONFIG
$config['upload_path'] = '/assets/dist/foto_validasi';
$config['allowed_types'] = 'jpg|png';
$config['file_name'] = date('ymd');
$this->load->library('upload', $config);
if(!$this->upload->do_upload('pict')){
echo "Upload Failed";
}else{
$pict = $this->upload->data('file_name');
}
$data = [
'user_name' => $username,
'email' => $email,
'password' => $password,
'role' => 'pengguna',
'img' => $pict,
'status_aktivasi' => 'tidak aktif',
'created_by' => 'SYSTEM',
];
$this->m_auth->registrasi($data, 'tb_m_user');
$this->session->set_flashdata('success' , 'Registration Successful! Please Login');
Redirect('Auth/login');
}
}
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('auth/login');
}else{
$this->postlogin();
}
}
Here is my form View :
<?= form_open_multipart('Auth/registrasi'); ?>
<div class="border-top mt-3">
<div class="ml-2">
<label class="mt-2">Upload Kartu Identitas</label>
</div>
<div class="input-group mb-3">
<input type="file" class="form-control" placeholder="Upload Foto Identitas" name="pict">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-file-image"></span>
</div>
</div>
</div>
<small class="text-danger"><?= form_error('foto') ?></small>
</div>
<?= form_close(); ?>
Here is the error : error
I even tried to change the variabel from:
$pict = $this->upload->data('file_name');
'img' => $pict,
to :
$pict2 = $this->upload->data('file_name');
'img' => $pict2,
but it gets another error :error2
If you want the upload feature to be required, you could modify the codes like this :
public function registrasi() {
//VALIDATION
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tb_m_user.email]');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]|matches[konfirmasi_password]');
$this->form_validation->set_rules('konfirmasi_password', 'Retype Password', 'required|trim|matches[password]');
if($this->form_validation->run() == false) {
$this->session->set_flashdata('fail' , 'Registration Failed! Please Try Again');
$this->load->view('auth/registrasi');
}else{
//INSERT TO DATABASE
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
$pict = $_FILES['pict'];
//LIBRARY UPLOAD CONFIG
$config['upload_path'] = '/assets/dist/foto_validasi';
$config['allowed_types'] = 'jpg|png';
$config['file_name'] = date('ymd');
$this->load->library('upload', $config);
if(!$this->upload->do_upload('foto')){
echo "Upload Failed";
$this->session->set_flashdata('fail', $this->upload->display_errors() );
redirect( 'auth/registrasi' );
}else{
$pict = $this->upload->data('file_name');
$data = [
'user_name' => $username,
'email' => $email,
'password' => $password,
'role' => 'pengguna',
'img' => $pict,
'status_aktivasi' => 'tidak aktif',
'created_by' => 'SYSTEM',
];
$this->m_auth->registrasi($data, 'tb_m_user');
$this->session->set_flashdata('success' , 'Registration Successful! Please Login');
Redirect('Auth/login');
}
}
}
The $this->upload->display_errors() code will display the error message on the uploaded file that does not meet the requirements, so if the file is not uploaded then the registration data will not be saved.
Change the post field name as if(!$this->upload->do_upload('pict')){
if(!$this->upload->do_upload('pict')){ // You should change this
size attribute should be there in input field
<input type="file" size="1" class="form-control" placeholder="Upload Foto Identitas" name="pict">
Related
View:
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<form method="post" action="<?php echo base_url();?>account/register">
<?php $form_error = $this->session->flashdata('error'); ?>
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" type="input">
<div id="form_error"><?php echo $form_error['username']; ?></div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" id="password" name="password" type="password">
<div id="form_error"><?php echo $form_error['password']; ?></div>
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password</label>
<input class="form-control" id="confirm_password" name="confirm_password" type="password">
<div id="form_error"><?php echo $form_error['confirm_password']; ?></div>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select class="form-control" id="gender" name="gender">
<option disabled selected value="">select a gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<div id="form_error"><?php echo $form_error['gender']; ?></div>
</div>
<div class="form-group">
<label for="birthdate">Birthdate</label>
<input class="form-control" id="birthdate" name="birthdate" type="date">
<div id="form_error"><?php echo $form_error['birthdate']; ?></div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="<?php echo base_url();?>pages/login_user">Already have an account?</a>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
Account Controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date');
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
echo 'aw';
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{
echo $birthdate;
$this->form_validation->set_message('valid_date', 'Invalid Birthdate');
$form_error['birthdate'] = form_error('valid_date');
$this->session->set_flashdata('error',$form_error);
return FALSE; }
}
Pages Controller:
public function login_user(){
$data['title'] = 'Login';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/login');
$this->load->view('template/footer');
}
public function register_user(){
$data['title'] = 'Register';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/registration');
$this->load->view('template/footer');
}
I tried setting flashdata inside the callback function but this is my first time using a callback function to check the validity of the birthdate given. I tested out the input and you can't input any alphabets but you can go over the maximum length. For example the format should be 'YYYY-MM-DD' you can input something like this: 555555-55-55.
All my other error prints out successfully but the valid_date callback function prints an error:
Unable to access an error message corresponding to your field name
Birthdate.(valid_date)
If what i'm asking for is impossible/wrong then i'll just add a min_length[10] and max_length[10] and just edit its error to 'invalid date'.
EDIT: Taking inspiration from my statement above about the max and min length, i also added a custom error for the valid_date there and what do you know it works.
Heres my updated controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date',
array('valid_date' => 'Invalid Date of birth'));
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{return FALSE; }
}
I'm still not sure if it really works or just by fluke.
Register code:
public function register() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
if ($this->form_validation->run() == FALSE) {
// let's see what's going on under the hood...
print_r($this->form_validation->error_array());
exit;
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
} else {
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d', time()),
'last_login' => mdate('%Y-%m-%d', time()));
if ($this->account_model->create_account($data)) {
$this->session->set_flashdata('message', 'Registration Successful');
redirect('pages/login_user');
} else {
$this->session->set_flashdata('message', 'Registration Failed');
redirect('pages/register_user');
}
}
}
Referencing a callback necessitates the function be called via callback_func_name.
Revised callback:
Note: item does not start with callback_
See: Correctly determine if date string is a valid date in that format (read: test cases)
public function valid_date($date) {
$format = 'Y-m-d';
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) == $date) {
return TRUE;
} else {
$this->form_validation->set_message('valid_date', 'Invalid Birthdate.');
return FALSE;
}
}
Doing date('YYYY-MM-DD') is wrong as it yields: 2018201820182018-FebFeb-SatSat. See date docs.
You should call this way:
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
hey try this to use callback
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_validdate',
//form_validation callback
public function validdate($birthdate){
$birthdate = $this->input->post('birthdate');
if( date('YYYY-MM-DD',strtotime($birthdate)) )
{
return true;
}
$this->form_validation->set_message('validdate','Check the birthday input to match a format like this YYYY-MM-DD');
return false;
}
Callbacks: Your own Validation Methods
The validation system supports callbacks to your own validation methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback method that does that
More Detail read https://codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
The one problem which I can not resolve in while, i tried every possible solution but I doesn't go well
Well, the problem is when I want to upload image, i select image from my comp and when I click submit button, image is not upload, and it's show me defaule image which i put in a case that user doesn't select image (noimage.jpg)
Function for upload image start in create() method
Posts Controller
<?php
class Posts extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->database();
$this->load->library('upload');
}
public function index($offset = 0){
$config['base_url'] = base_url() . 'posts/index/';
$config['total_rows'] = $this->db->count_all('posts');
$config['per_page'] = 3;
$config['uri_segment'] = 3;
$config['attributes'] = array('class' => 'pagination-link');
$this->pagination->initialize($config);
$data['posts']= $this->Posts_model->get_posts(FALSE,$config['per_page'],$offset);
$this->load->view('templates/header');
$this->load->view('posts/index',$data);
$this->load->view('templates/footer');
}
public function view($mjestoOdredista=NULL){
$data['posts'] = $this->Posts_model->get_posts($mjestoOdredista);
$post_id = $data['posts']['id'];
$data['comments'] = $this->comment_model->get_comments($post_id);
if(empty($data['posts'])){
show_404();
}
$data['id'] =$data['posts'];
$this->load->view('templates/header');
$this->load->view('posts/view',$data);
$this->load->view('templates/footer');
}
public function create(){
//check if user is logged in
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('mjestoPolaska', 'Mjesto Polaska', 'required');
$this->form_validation->set_rules('mjestoOdredista', 'Mjesto Odredista', 'required');
$this->form_validation->set_rules('datumPolaska', 'Datum Polaska', 'required');
$this->form_validation->set_rules('datumPovratka', 'Datum Povratka', 'required');
$this->form_validation->set_rules('cijena', 'Cijena', 'required');
$this->form_validation->set_rules('brojMjesta', 'Broj mjesta', 'required');
$this->form_validation->set_rules('opis', 'Opis', 'required');
$data['title'] ='Create Posts';
$data['categories'] = $this->Posts_model->get_categories();
if($this->form_validation->run()===FALSE){
$this->load->view('templates/header');
$this->load->view('posts/create',$data);
$this->load->view('templates/footer');
}else {
//upload image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '100';
$config['max_height'] = '100';
$this->load->library('upload',$config);
if(!$this->upload->do_upload('userfile')){
$errors = array('error'=>$this->upload->display_errors());
$post_image='noimage.jpg';
}else{
$data = array('upload_data'=>$this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->create_post($post_image);
$this->session->set_flashdata('post_creted', 'You post has been created') ;
redirect('posts');
}
}
public function delete($id){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->Posts_model->delete_post($id);
$this->session->set_flashdata('post_deleted', 'You post has been deleted ') ;
redirect('posts');
}
public function edit($mjestoOdredista){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$data['posts']= $this->Posts_model->get_posts($mjestoOdredista);
//Check if user is logged in
if($this->session->userdata('user_id') != $this->Posts_model->get_posts($mjestoOdredista)['user_id']){
redirect('posts');
}
$data['categories'] = $this->Posts_model->get_categories();
if(empty($data['posts'])){
show_404();
}
$data['title'] = 'Edit Post';
$this->load->view('templates/header');
$this->load->view('posts/edit',$data);
$this->load->view('templates/footer');
}
public function update(){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->Posts_model->update_post();
$this->session->set_flashdata('post_updated', 'You post has been updated ') ;
redirect('posts');
}
}
?>
Posts_model
<?php
class Posts_Model extends CI_Model{
public function __construct(){
$this->load->database();
}
function get_posts($mjestoOdredista=FALSE, $limit = FALSE,$offset = FALSE){
if($limit){
$this->db->limit($limit,$offset);
}
if($mjestoOdredista === FALSE){
$this->db->order_by('posts.id','DESC');
$this->db->join('categories','categories.id = posts.category_id');
$query=$this->db->get('posts');
return $query->result_array();
}
$query=$this->db->get_where('posts', array('mjestoOdredista' => $mjestoOdredista));
return $query->row_array();
}
//Kreiranje post
public function create_post($post_image){
$mjestoPolaska = url_title($this->input->post('title'));
$data=array(
'mjestoPolaska' => $this->input->post('mjestoPolaska'),
'mjestoOdredista' => $this->input ->post('mjestoOdredista'),
'datumPolaska' => $this->input ->post('datumPolaska'),
'datumPovratka' => $this->input ->post('datumPovratka'),
'brojMjesta' => $this->input ->post('brojMjesta'),
'cijena' => $this->input ->post('cijena'),
'opis' => $this->input ->post('opis'),
'category_id'=>$this->input->post('category_id'),
'user_id' =>$this->session->userdata('user_id'),
'post_image'=>$post_image
);
return $this->db->insert('posts',$data);
}
//Brisanje posta
public function delete_post($id){
$this->db->where('id',$id);
$this->db->delete('posts');
return true;
}
//editovanje posta
public function update_post(){
$mjestoOdredista = url_title($this->input->post('title'));
$data=array(
'category_id' => $this->input->post('category_id'),
'mjestoPolaska' => $this->input->post('mjestoPolaska'),
'mjestoOdredista' => $this->input->post('mjestoOdredista'),
'datumPolaska' => $this->input ->post('datumPolaska'),
'datumPovratka' => $this->input ->post('datumPovratka'),
'cijena' => $this->input ->post('cijena'),
'brojMjesta' => $this->input ->post('brojMjesta'),
'opis' => $this->input ->post('opis'),
);
$this->db->where('id', $this->input->post('id'));
return $this->db->update('posts', $data);
}
public function get_categories(){
$this->db->order_by('name');
$query = $this->db->get('categories');
return $query->result_array();
}
public function get_posts_by_category($category_id){
$this->db->order_by('posts.id','DESC');
$this->db->join('categories','categories.id = posts.category_id');
$query=$this->db->get_where('posts',array('category_id'=> $category_id));
return $query->result_array();
}
}
?>
Create View
<h2><?= $title;?></h2>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$("#datepicker").datepicker({
dateFormat: 'dd-mm-yy'
});
$("#datepicker1").datepicker({
dateFormat: 'dd-mm-yy'
});
});
</script>
<?php echo form_open_multipart('posts/create/');?>
<?php echo validation_errors();?>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label>Mjesto Polaska</label>
<input type="text" class="form-control" name="mjestoPolaska" placeholder="Mjesto Polaska">
</div>
<div class="form-group">
<label>Mjesto Odredista</label>
<input type="text" class="form-control" name="mjestoOdredista" placeholder="Mjesto Odredista">
</div>
<div class="form-group">
<label>Datum Polaska</label>
<input type="date" id="datepicker" class="form-control" name="datumPolaska" placeholder ="Datum Polaska" >
</div>
<div class="form-group">
<label>Datum Povratka</label>
<input type="date" id="datepicker1" class="form-control" name="datumPovratka" placeholder="Datum Povratka">
</div>
<div class="form-group">
<label>Cijena</label>
<input type="text" class="form-control" name="cijena" placeholder="Cijena">
</div>
<div class="form-group">
<label for="select">Broj slobodnih mjesta</label>
<select class="form-control" id="select" name="brojMjesta">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
<div class="form-group">
<label for="kategorije">Kategorija</label>
<?php
echo '<select class="form-control" id="kategorije" name="category_id">';
foreach($categories as $category) :
echo '<option value="' . $category['id'] . '">' . $category["name"] . '</option>';
endforeach;
echo '</select>';
?>
</div>
<div class="form-group">
<label>Postavi sliku:</label>
<p><b>samo oni koji nude prevoz nek postave sliku svojeg vozila</b></p>
<input type="file" name="userfile" size="20">
</div>
<div class="form-group">
<label>Opis:</label>
<textarea class="form-control" rows="5" id="comment" name="opis"></textarea>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
if store data without image then
public function create() {
//check if user is logged in
if (!$this->session->userdata('logged_in')) {
redirect('users/login');
}
$this->form_validation->set_rules('mjestoPolaska', 'Mjesto Polaska', 'required');
$this->form_validation->set_rules('mjestoOdredista', 'Mjesto Odredista', 'required');
$this->form_validation->set_rules('datumPolaska', 'Datum Polaska', 'required');
$this->form_validation->set_rules('datumPovratka', 'Datum Povratka', 'required');
$this->form_validation->set_rules('cijena', 'Cijena', 'required');
$this->form_validation->set_rules('brojMjesta', 'Broj mjesta', 'required');
$this->form_validation->set_rules('opis', 'Opis', 'required');
$data['title'] = 'Create Posts';
$data['categories'] = $this->Posts_model->get_categories();
if ($this->form_validation->run() === FALSE) {
$this->session->set_flashdata("error", validation_errors());
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
$post_image='';
if (!empty($_FILES['userfile']['name'])) {
$path = 'assets/images/posts/';
$post_image = $this->ImageUpload($path, 'userfile', '');
if (!is_array($post_image)) {
$this->session->set_flashdata('error', $post_image);
redirect(site_url() . 'posts/create');
}
$post_image = $post_image['file_name'];
}
$this->Posts_model->create_post($post_image);
$this->session->set_flashdata('post_creted', 'You post has been created');
redirect('posts');
}
}
Try This
Replace your create function with this code
public function create()
{
//check if user is logged in
if (!$this->session->userdata('logged_in')) {
redirect('users/login');
}
$this->form_validation->set_rules('mjestoPolaska', 'Mjesto Polaska', 'required');
$this->form_validation->set_rules('mjestoOdredista', 'Mjesto Odredista', 'required');
$this->form_validation->set_rules('datumPolaska', 'Datum Polaska', 'required');
$this->form_validation->set_rules('datumPovratka', 'Datum Povratka', 'required');
$this->form_validation->set_rules('cijena', 'Cijena', 'required');
$this->form_validation->set_rules('brojMjesta', 'Broj mjesta', 'required');
$this->form_validation->set_rules('opis', 'Opis', 'required');
$data['title'] = 'Create Posts';
$data['categories'] = $this->Posts_model->get_categories();
if ($this->form_validation->run() === FALSE) {
$this->session->set_flashdata("error", validation_errors());
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
if (empty($_FILES['userfile']['name'])) {
$this->session->set_flashdata('error', "Please select image");
redirect(site_url() . 'posts/create');
}
$path = 'assets/images/posts/';
$post_image = $this->ImageUpload($path, 'userfile', '');
if (!is_array($post_image)) {
$this->session->set_flashdata('error', $post_image);
redirect(site_url() . 'posts/create');
}
$post_image = $post_image['file_name'];
$this->Posts_model->create_post($post_image);
$this->session->set_flashdata('post_creted', 'You post has been created');
redirect('posts');
}
}
public function ImageUpload($upload_path, $uploading_file_name, $file_name = '') {
$obj = &get_instance();
$obj->load->library('upload');
//echo $uploading_file_name.$file_name;
$file_name = 'image_' . time() . $file_name . "." . pathinfo($_FILES[$uploading_file_name]['name'], PATHINFO_EXTENSION);
$full_path = FCPATH . $upload_path;
// $full_path = $upload_path;// uncomment if you using windows os
// if folder is not exists then create the folder
//if (!is_dir($full_path)) {
// mkdir($full_path, 0775);
//}
$config['upload_path'] = $full_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg|GIF|JPG|PNG|JPEG';
$config['max_size'] = 2048;
$config['max_width'] = 2048;
$config['max_height'] = 2048;
$config['file_name'] = $file_name;
$obj->upload->initialize($config);
if (!$obj->upload->do_upload($uploading_file_name)) {
return $obj->upload->display_errors();
} else {
return $obj->upload->data();
}
}
And Replace <?php echo validation_errors();?> to <?php echo $this->session->flashdata("error")?>
Or you can use layout library instead of calling header n footer [https://code.tutsplus.com/tutorials/how-to-create-a-layout-manager-with-codeigniter--net-15533]
FCPATH works fine in linux system only so check FCPATH if error come path is wrong
I am trying to submit a feedback after logging in the user. The Data in not being inserted in the database nor is it displaying any message if the form is left empty.
This is my controller:
function dashboard(){
$this->load->model('stud_model');
$this->form_validation->set_rules('name','Name', 'required');
$this->form_validation->set_rules('email', 'Email Id', 'required');
$this->form_validation->set_rules('feedback', 'Feedback', 'required');
$data['username'] = $this->session->userdata('username');
if ($this->form_validation->run()) {
$data = array(
'Name' => $this->input->post('name'),
'Email' => $this->input->post('email'),
'Feedback' => $this->input->post('feedback'),
);
$submit = $this->stud_model->insert_feedback($data);
if($submit) {
$this->session->set_flashdata('message', 'Feedback Successfully Submitted !');
redirect('Students/enter');
}else{
$this->session->set_flashdata('message', 'Feedback could not be Submitted !');
redirect('Students/enter');
}
}else{$this->load->View('dashboard', $data);}
}
function enter(){
if ($this->session->userdata('username') != '') {
$data['username'] = $this->session->userdata('username');
$this->load->View('dashboard', $data);
}else{
redirect('Students/log');
}
}
function logout(){
$this->session->unset_userdata('username');
redirect('Students/index');
}
This is my view:
<body>
<h1 align="center">My Dashboard</h1><br><br>
<h3 align="left">Welcome <?php echo $username ?> !</h3>
<form action="http://localhost/ci/index.php/Students/dashboard" align="center">
<?php echo validation_errors(); ?>
<br>
<input type="hidden" name="name" value="<?php echo $username ?>"><br>
Email Id : <br><input type="text" name="email"><br><br>
Feedback:<br><br>
<textarea name="feedback" rows="10" cols="50"></textarea><br><br>
<input type="submit" value="Submit"><br><br>
<?php echo $this->session->flashdata("message"); ?>
Logout
</form>
</body>
This is my Model:
function insert_feedback($data){
$this->load->database();
$this->db->insert("feedback", $data);
return $this->db->insert_id();
}
I think you use
$this->load->library('database');
Instead
$this->load->database();
Change setting on config folder in autoload.php
$autoload['libraries'] = array('database','form_validation', 'session');
$autoload['helper'] = array('url','form');
Got the Error myself.
I had forgot to add 'method="post"' to my form.
I have the form field like
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php if($user->postal_code === NULL) { echo set_value('postal_code');} else { echo $user->postal_code;} ?>">
<label for="form_control_1">Postal Code</label>
<span class="help-block">Postal Code is required</span>
and my function is
public function postProfile() {
if ($_POST) {
$this->form_validation->set_rules('postal_code', 'Postal Code', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('month', 'Month', 'required');
$this->form_validation->set_rules('day', 'Day', 'required');
$this->form_validation->set_rules('year', 'Year', 'required');
$this->form_validation->set_rules('mobile_number', 'Mobile Number', 'required');
if ($this->form_validation->run() === FALSE) {
//$this->session->set_flashdata('err', validation_errors());
$this->session->set_flashdata('email_err', form_error('email'));
$this->session->set_flashdata('postal_code_err', form_error('postal_code'));
$this->session->set_flashdata('gender_err', form_error('gender'));
$this->session->set_flashdata('country_err', form_error('country'));
$this->session->set_flashdata('day_err', form_error('day'));
$this->session->set_flashdata('year_err', form_error('year'));
$this->session->set_flashdata('month_err', form_error('month'));
$this->session->set_flashdata('mobile_err', form_error('mobile_number'));
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
$dob = $this->input->post('month') . '/' . $this->input->post('day') . '/' . $this->input->post('year');
$userData = array(
'email' => $this->input->post('email'),
'date_of_birth' => $dob,
'gender' => $this->input->post('gender'),
'country' => $this->input->post('country'),
'mobile_number' => $this->input->post('mobile_number'),
'postal_code' => $this->input->post('postal_code'),
);
$updateUser = $this->user->updateUser($this->session->userdata['front']['id'], $userData);
if ($updateUser) {
$this->session->set_flashdata('err', '<div class="alert alert-success">Profile Updated Successfuly</div>');
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
echo "Un expected error ";
exit;
}
}
} else {
$this->logout();
}
}
but value is not shown for the postal code field in case of validation errors
When error occur then you need to render view instead of rediect().
if ($this->form_validation->run() == FALSE) {
// no need to set_flashdata here for form_error()
$this->load->view('view_form',$data);
return;
}else{
//success code
}
Now view file
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php echo set_value('postal_code');?>">
<?php echo form_error('postal_code','<p class="alert alert-danger">','</p>');?>
Now your form will repopulate previous data if any error occur. In the same time you will see error message under your postal_code field
You can set these values in flashdata and redirect to your form. For example
if ($this->form_validation->run() == FALSE) {
$data = array(
'errors' => validation_errors(),
'name' => $this->input->post('name')//check this
);
$this->session->set_flashdata($data);
redirect('YOUR-URL-HERE');
}
And in your form use value attribute of form input as given below
<input type="text" class="form-control" name="name" placeholder="Name" value="<?= $this->session->flashdata('name'); ?>">
I have created a form in Codeigniter but it does not to submit values to the database. I have tried to debug my code by echoing out "hello" in my method that works but the actual method does not submit anything to the database.
This is code in my view page
<div data-role="content">
<?php echo form_open('index.php/welcome/adduser'); ?>
<div data-role="fieldcontain">
<?php echo validation_errors('<p class="error">','</p>'); ?>
<p>
<label>Firstname: </label>
<?php echo form_input('firstname', set_value( 'firstname' ) ); ?>
</p>
<p>
<label>Lastname: </label>
<?php echo form_input('lastname', set_value( 'lastname' ) ); ?>
</p>
<p>
<label>Email: </label>
<?php echo form_input('email', set_value( 'email' ) ); ?>
</p>
<p>
<label>Age: </label>
<?php echo form_input('age', set_value( 'age' ) ); ?>
</p>
<p>
<label>username: </label>
<?php echo form_input('username', set_value( 'username' ) ); ?>
</p>
<p>
<label>Password: </label>
<?php echo form_input('password', set_value( 'password' ) ); ?>
</p>
<p>
<?php echo form_submit('submit', 'Submit'); ?>
</p>
</div>
This is my controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Welcome extends CI_Controller {
/** loading services* */
function __construct() {
parent::__construct();
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
}
/** loading several pages * */
public function index() {
$this->load->view('abt-header');
$this->load->view('abt-abovetheblues');
$this->load->view('abt-footer');
}
public function adduser() {
if ($this->_adduser_validate() === FALSE) {
$this->index();
return;
}
$data = new user();
$data->firstname = $this->input->post('firstname');
$data->lastname = $this->input->post('lastname');
$data->username = $this->input->post('username');
$data->password = $this->input->post('password');
$data->email = $this->input->post('email');
$data->age = $this->input->post('age');
$this->load->view('#abt-profile');
}
private function _adduser_validate() {
// validation rules
$this->form_validation->set_rules('firstname', 'Firstname', 'required');
$this->form_validation->set_rules('lastname', 'Lastname', 'required');
$this->form_validation->set_rules('username', 'Username', 'required|alpha_numeric|min_length[6]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[12]');
// $this->form_validation->set_rules('passconf', 'Confirm Password', 'required|matches[password]');
$this->form_validation->set_rules('email', 'E-mail', 'required|valid_email');
$this->form_validation->set_rules('age', 'Age', 'required');
return $this->form_validation->run();
}
}
?>
You are not specifying what data to be saved in which table.
Use something like this...
/*
$data = array(
'tableCol1' => $this->input->post('postedItem1'),
'tableCol2' => $this->input->post('postedItem2'),
);
*/
$this->db->set($data);
$this->db->insert($tableName);
First of all you have not closed your form, add this to your view:
<?php echo form_close();?>
I don't see where you have run your insert query which will insert data in database. Your Adduser function can be like this:
public function adduser() {
if ($this->_adduser_validate() === FALSE) {
$this->index();
return;
}
$data = array(
'firstname' = $this->input->post('firstname'),
'lastname' = $this->input->post('lastname'),
'username' = $this->input->post('username'),
'password' = $this->input->post('password'),
'email' = $this->input->post('email'),
'age' = $this->input->post('age'),
);
$this->db->insert('user',$data);
$this->load->view('#abt-profile');
}
I am assuming you have set your database name and login credentials in config/database.php file
This will for sure help you. If there is any problem let me know.