Unidentified Property in Control in my codeigniter framework - php

I am new to frameworks and trying to send values to database table, I have done it simply but now I am using templates (the famous alemsaeed free AdminLTE) now after setting BASEPATH and giving database connection in database.php,I am still getting errors.
However the code looks fine but I don't know please kindly tell me the reason it's my 2nd week in codeigniter.
MODEL
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mdl extends CI_Model {
function __construct() {
parent::__construct();
}
function form_insert($data){
$data = array(
'name' => $this->input->post('name'),
'fname' => $this->input->post('fname'),
'dob' =>$this->input->post('dob')
);
$this->db->insert('folio', $data);
}
}
?>
Controller
public function index() {
$this->load->helper(array('form','url'));
$this->load->view('myself');
}
public function eid() {
$this->load->helper(array('form','url'));
$this->load->database();
$this->load->model('mdl');
$this->model->form_insert();
$this->load->view('edu');
}
}
?>
View
Note:i have shorted the whole view code because it's a template
For Form Loading the usual
<?php
echo form_open(site_url().'/ctrl/eid/');
$attributes = array('class' => 'sidebar-form');
?>
<label>Enter Your Name</label>
<input type="text" class="form-control" placeholder="YourName" name="name">
<label>Father Name</label>
<input type="text" class="form-control" name="fname" placeholder="father name">
<input type="date" class="form-control" name="dob" placeholder="DD/MM/YYYY" >
<button type="submit" class="btn btn-info pull-right">Submit</button>
</div>
<div class="box-footer">
Copyright © 2015-2016 PIET MULTAN.</strong> All rights reserved.
</div>
</div>

Remove argument $data from form_insert method of model. Like: public function form_insert() {/* rest of code here */} because you are not passing anything from controller. Although I would advice you that you do that passing from controller like:
public function eid()
{
//controller
$data = array();
$data['name'] => $this->input->post('name'),
$data['fname'] => $this->input->post('fname'),
$data['dob'] =>$this->input->post('dob'),
$this->load->helper(array('form','url'));
$this->load->database();
$this->load->model('mdl');
if ( $this->model->form_insert($data) )
{
//success view
}
else
{
//insert fail view
}
}
function form_insert($data)
{
//model
$this->db->insert('folio', $data);
return $this->db->affected_rows() > 0;
}

In Controller
function __construct()
{
parent::__construct();
//load default helpers in this
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('mdl');
}
public function index()
{
$this->load->view('myself');
}
public function eid()
{
$name = $_POST['name'];
$fname = $_POST['fname'];
$dob = $_POST['dob'];
if(!empty($name) || !empty($fname) || !empty($dob))
{
$this->Mdl->form_insert($name, $fname, $dob);//Model name should be Mdl
$this->load->view('edu');
}
else
{
//fields are empty
}
}
In Model
function form_insert($name, $fname, $dob)
{
$data = array(
'name' => $name,
'fname' => $fname,
'dob' => $dob
);
$this->db->insert('folio', $data);
}
In View (Form should be)
<form action="<?php echo base_url();?>index.php/ctrl/eid" method="post" class="sidebar-form">
<label>Enter Your Name</label>
<input type="text" class="form-control" placeholder="YourName" name="name">
<label>Father Name</label>
<input type="text" class="form-control" name="fname" placeholder="father name">
<label>Date Of Birth</label>
<input type="date" class="form-control" name="dob" placeholder="DD/MM/YYYY" >
<button type="submit" class="btn btn-info pull-right">Submit</button>
</form>

The Problem was in the Controller
it should be the modelfileName not model in the code where we load the function
$this->mdl->form_insert();
And this did work :D
The Next problem was in the sitemap
it was this before
$config['site_url']='../../folio/';
instead of this
$config['site_url']='http://localhost/folio/index.php/';
But Once Again i appreciate all for your help it really means to me a lot .
THK_STACOVRFLW

Related

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. i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops!
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
<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
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. 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... and get more details on the error.
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).
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. 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. 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
<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

How to insert form value in ci?

controller: Test.php
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
$this->Users_model->insert_user();
$this->load->view('home');
}
}
?>
Model: User_model.php
<?php
class Users_model extends CI_Model
{
public function insert_user()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'message' => $this->input->post('message')
);
return $this->db->insert('user', $data);
}
}
?>
view: home.php
<form method="post">
<label for="name">your Name</label>
<input class="form-control" id="name" type="text" placeholder="Name" name="name" />
<label for="email">Your email</label>
<input class="form-control" id="email" type="text" placeholder="Email" name="email" />
<label for="message">Your Message</label>
<textarea class="form-control" id="message" placeholder="Message" name="message"></textarea>
<button type="submit">send</button>
</form>
I am new in codeigniter here I want to insert form value into database but it showing some error i.e.
how can I fix this error ? please help.
Thank You
You got the errors because you call User_model->insert_user() before any data submitted in the form. You should check if there is any posted data then save to the database. Here is the example of your controller should be:
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
// do checking right here
if (!empty($this->input->post('name'))) {
$this->Users_model->insert_user();
}
$this->load->view('home');
}
}
You forget to pass POST data in insert method of model in controller .
Contoller
<?php
class Test extends CI_Controller {
public function index()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'message' => $this->input->post('message')
);
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
$this->Users_model->insert_user($data );
$this->load->view('home');
}
}
Model
<?php
class Users_model extends CI_Model
{
public function insert_user($data = [])
{
return $this->db->insert('user', $data);
}
}
?>
You extend CI_Model But did not call parent construct. Use this:
function __construct() {
// Call the Model constructor
parent :: __construct();
}
Hope this will work. Thanks.
In your "home.php" you haven't specify an action attribute. Due to this form value is not posting.
for example:- <form action="<?php echo base_url();?>YourfileName/DeclaredFunctionName" method="post">
and then try to fetch the value of your form in your controller.
In controller please execute this function insert_user() { print_r($_POST); exit(); }
If you are getting values in your browser, then remove exit() and execute your code. Otherwise, please share your error here.
Thanks

Refreshing page null record automatically inserting in database

I am using codeigniter MVC pattern . Whenever i am refreshing the page, Null record automatically inserting in database. In database, I set the all column as null except primary key.
Please help me.
View page code(index.php)
<div class="title">
<p><strong>ADD USER</strong></p>
</div>
<?php echo form_open("Welcome/index"); ?>
<input type="text" name="userId" placeholder="USER ID" style="width:500px">
<input type="date" name="date" style="width:500px">
<input type="text" name="firtsname" placeholder="FIRST NAME" style="width:330px">
<input type="text" name="middlename" placeholder="MIDDLE NAME" style="width:330px">
<input type="text" name="lastname" placeholder="LAST NAME" style="width:330px">
<input type="text" name="mobileno" placeholder="ENTER MOBILE NO." style="width:500px">
<input type="text" name="landline" placeholder="LANDLINE No." style="width:500px">
<textarea name="address" placeholder="ENTER ADDRESS"></textarea>
<input type="text" name="city" placeholder="CITY" style="width:500px">
<input type="text" name="locality" placeholder="LOCALITY" style="width:500px">
<input type="text" name="email" placeholder="ENTER EMAIL" style="width:1010px"></br>
<input type="submit" class="submit" name="SUBMIT">
<?php echo form_close(); ?>
</div>
Model page code(model_add_user.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Model_add_user extends CI_Model {
public function __construct() {
parent:: __construct();
$this->load->database();
}
public function add_user() {
$data = array(
'userId' => $this->input->post('userId'),
'date' => $this->input->post('date'),
'firtsname' => $this->input->post('firtsname'),
'middlename' => $this->input->post('middlename'),
'lastname' => $this->input->post('lastname'),
'mobileno' => $this->input->post('mobileno'),
'landline' => $this->input->post('landline'),
'address' => $this->input->post('address'),
'city' => $this->input->post('city'),
'locality' => $this->input->post('locality'),
'email' => $this->input->post('email'),
);
$this->db->insert('add_user', $data);
}
}
?>
Controller page code(Welcome.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
//$this->load->view('welcome_message');
$this->load->view('index');
$this->load->model('model_add_user');
$this->model_add_user->add_user();
}
}
?>
In your controller make the following change :
public function index() {
if ($this->input->post()) {
$this->load->model('model_add_user');
$this->model_add_user->add_user();
}
$this->load->view('index');
}
Path up to controller name directly hit the index function of your controller. Here in your code you load view and call add_user function.So every time you refresh the page your model call and null insert into your database
You need to create a separate function for your insert data
public function index()
{
//$this->load->view('welcome_message');
$this->load->view('index');
}
function add_user()
{
$this->load->model('model_add_user');
$this->model_add_user->add_user();
}
And change form action to
<?php echo form_open("Welcome/add_user"); ?>
After successful insertion.. Just redirect it to... function / controller it will refresh the page and prevent the form submission again.
public function index() {
//$this->load->view('welcome_message');
$this->form_validation->set_rules('field', 'Field', 'trim|required');
if ($this->form_validation->run()) {
$this->load->model('model_add_user');
$this->model_add_user->add_user();
redirect('welcome')
} else {
$this->load->view('index');
}
}

codeigniter form not submitting data

I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.

Using Cjax to POST data in CodeIgniter

I'm trying to POST some data using Cjax in CodeIgniter.
My view is:
<?php
require_once(FCPATH . 'ajaxfw.php');
$ajax->click('#subscribesubmit' , $ajax->form('ajax.php?subscriber/add/'));
?>
<div class="col-md-4">
<form class="form-inline subscribe-box" role="form" method="post">
<div class="form-group">
<label class="sr-only" for="subscribemail">Email address</label>
<input type="text" class="form-control" id="subscribemail" name="subscribemail" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="subscribesubmit">Subscribe</button>
</form>
</div>
This view is loaded in controller index().
My subscriber controller:
class Subscriber extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('email');
$this->load->model('subscriber_model');
require_once(FCPATH.'ajaxfw.php');
}
public function add($subscribemail) {
$ajax = ajax();
//$email = $this->input->post('subscribemail');
echo $subscribemail;
$data['status'] = $this->subscriber_model->new_subscriber($subscribemail);
}
}
}
Try this:
in your code block replace to:
require_once(FCPATH . 'ajax.php');
instead of:
require_once(FCPATH . 'ajaxfw.php');
You should include ajax.php instead of ajaxfw.php (ajax.php would include itself ajaxfw.php if it needs to)

Categories