trying to insert form values into database using codeigniter but nothing heppens.
my form is comment_form.php is like,
<?php echo validation_errors(); ?>
<?php echo form_open('news/comment_form'); ?>
Name<input type="text" name="comment_name"></input><br />
Email<input type="text" name="comment_email"></input><br />
Comment<input type="text" name="comment_body"></input><br />
<input type="submit" name="submit" value="Comment it" ></input>
</form>
here's my controller comments.php
class Comments extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('comment_model');
}
public function create_comment()
{
$this->load->helper('form');
$this->load->library('form_validation');
//$data['title'] = 'Create a news item';
$this->form_validation->set_rules('comment_name', 'comment_name', 'required');
$this->form_validation->set_rules('comment_email', 'comment_email', 'required');
$this->form_validation->set_rules('comment_body', 'comment_body', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/comment_form');
$this->load->view('templates/footer');
} else {
$this->news_model->set_comment();
$this->load->view('news/success');
}
}
}
and this is my model comment_model.php
class Comment_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function set_comment()
{
//$this->load->helper('url');
//$slug = url_title($this->input->post('title'), 'dash', TRUE);
$datac = array(
'comment_name' => $this->input->post('comment_name'),
'comment_email' => $this->input->post('comment_email'),
'comment_body' => $this->input->post('comment_body')
);
return $this->db->insert('comments', $datac);
}
}
the problem is whenever i submitting the form it returns nothing, like nothing happened.please help.
In your comment_form.php change
echo form_open('news/create_comment');
to
echo form_open('comments/create_comment');
Why? Because the first parameter you give to form_open() is the action parameter. It will open a form tag like <form action="bla">. And news/create_comment is not the correct page you want to call. Your controller is named comments, that's why you put comments/create_comment.
In your comments.php change
$this->news_model->set_comment();
to
$this->comment_model->set_comment();
Why? Just simply pointing to the false model. Maybe a copypaste-error?
In your comment_model.php remove
$this->load->database();
And load it in your config.php (in the libraries array, add 'database').
Why? IMHO this is the more proper solution. You're probably gonna use your database pretty often, so why load that everytime?
If you still encounter problems, then we need more information. What exactly is not working. Do some debugging for us. After you call $this->news_model->set_comment() write var_dump($this->db->last_query());
this->news_model->set_comment()
Should be
this->comment_model->set_comment()
PS: sorry for the formatting. Mobile version doesn't read new lines.
Change :
$this->load->database();
echo form_open('news/comment_form');
$this->news_model->set_comment();
To:
$this->load->library('database');
echo form_open('news/create_comment');
$this->comment_model->set_comment();
It would be better if you load your database library in your autoload.php. Or in your controller's constructor.
In the set_comment function after $this->db->insert('comments', $datac); just echo the query using below command and try running the same query manually in the database, you may come to know the issue.
echo $this->db->last_query();
Get the posted values in controller instead of model and then pass them to model.
Controller function
public function create_comment()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('comment_name', 'comment_name', 'required');
$this->form_validation->set_rules('comment_email', 'comment_email', 'required');
$this->form_validation->set_rules('comment_body', 'comment_body', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/comment_form');
$this->load->view('templates/footer');
} else {
$data['comment_name'] = $this->input->post('comment_name'),
$data['comment_email'] = $this->input->post('comment_email'),
$data['comment_body'] = $this->input->post('comment_body')
$this->news_model->set_comment();
$this->load->view('news/success');
}
}
Model function
public function set_comment($data)
{
//$this->load->helper('url');
//$slug = url_title($this->input->post('title'), 'dash', TRUE);
$this->db->insert('comments', $data);
return $this->db->insert_id();
}
EDITS
The above code will work if you follow these steps.
Go to database.php in application/config and provide database connection settings like hostname , username , password and database name.
Then go to autoload.php in application/config and autoload the database library like this
$autoload['libraries'] = array('database');
Also remove the closing tags for input in your html form.
Try testing like this in controller before moving forward
$post = $this->input->post();
echo '<pre>';
print_r($post);
This will ensure you are receiving post data
Related
This is my route:
$route['pages/show_create']['GET'] = 'pages/show_create';
$route['pages/create']['POST'] = 'pages/create';
And this is my controller:
public function show_create()
{
$data['title'] = 'Create new news';
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
public function create()
{
$data['title'] = 'Create new news';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
I want to show the form by accessing news/show_create route but it just return 404. What's wrong with my code? Thanks
Codeigniter documentation is very easiest programming documentation. You can easily learn more about routing by using following link.
https://www.codeigniter.com/userguide3/general/routing.html
As i can see in your code you don't need to mentioned method type along with route.
Here i am assuming that you have got and PagesController class where you have created a method by using name show_create and for this you can set routing like below in your route class.If still you have confusion you can write here.
$route['news/show_create'] = 'pages/show_create';
Add this to your routes.
$route['news/show_create']['GET'] = 'pages/show_create';
I assumed your controller name is PageController.
This is the format.
$route['desired_route']['method'] = 'controller_name/function';
try this:
$route['news/show_create']='Controller_name/method_name';
It looks like you don't need routes. If they are removed, and assuming the controller is named pages, you can call the methods like so
http://example.com/pages/show_create
and
http://example.com/pages/create
If you truly want to show the form by accessing news/show_create then $route in Girraj's answer is the way to go.
$route['news/show_create'] = 'pages/show_create';
I am creating a form in codeignitor and every time I try to submit something the page does nothing in chrome or in firefox gives me this message:
The address wasn't understood
Firefox doesn't know how to open this address, because one of the
following protocols (localhost) isn't associated with any program or
is not allowed in this context.
You might need to install other software to open this address.
In internet explorer it trys to find an application to open the page.
I can access the same address directly but it won't let me do it when I submit the form.
this is the code for the form:
<?php
$hidden = array('account_id' => '1');
echo form_open('post', '', $hidden);
?>
<label for="post">Post:</label>
<input type="text" name="post" id="post"/>
<br/>
<input type="submit" value="post" />
</form>
This is the post controller:
<?php
class Post extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('posts_model');
$this->load->helper('url_helper');
$this->load->helper('form');
}
function index() {
$data['title'] = "posted";
$this->posts_model->add_post();
$this->load->view('templates/header', $data);
$this->load->view('comment/index', $data);
$this->load->view('templates/footer');
}
}
?>
This is the function in the posts_model:
function add_post() {
$data = array('person_acc_id' => $this-> input -> post('account_id'),
'post' => $this -> input -> post('post'),
'deleted' => 0,
'edited' => 0,
'post_time' => date('Y-m-d H:i:s', time()));
$this -> db -> insert('post', $data);
}
Actually you didn't set any method to form. Means your form action is Wrong.
In your function index() you call the view. So Then its load from in that. So if I click form submit <form> come to POST Controller. So it again execute function index() again. This will run like loop til you fix it.
So what you have to do is.
In controller Create new method to receive data
public function validate_form()
{
#your Form validate Code goes here
}
In view <form> should be
echo form_open('post/validate_form', '', $hidden);
this will act like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/post/validate_form" account_id="1" />
To Know about Form Validation
Just check your config.php in application/config, then change your link like this:
$config['base_url'] = 'http://localhost/yourApp/';
I guess your value before is like this:
$config['base_url'] = 'localhost/yourApp/';
My code was actually fine. Once I put it on a real server it works. It would not work with localhost.
I am new to codeigniter and trying to write an update function to update information in my database. I've gone through a few tutorials but for some reason my code is not working! Any tips or assistance would be greatly appreciated. I'm just testing with two fields right now, name and email, and I get a blank page when I go to my update view.
Here is my model method:
function get_by_id($id){
return $this->db->get_where('table',array('id'=>$id));
}
function update($id){
$attributes=array(
'name'=> $this->input->post('Name'),
'email'=> $this->input->post('Email')
);
return $this->db->where('id',$id)
->update('table',$attributes);
}
And here is my relevant controller code:
function edit(){
$data['row']=$this->Mymodel->get_by_id($id)->result();
$data['name']= 'Name';
$data['email']='Email';
$this->load->view('updateview', $data);
}
function update($id){
$this->load->model('Mymodel');
$this->Mymodel->update($id);
if($this->input->post()){
redirect('kittens/view/'.$id, 'refresh');
}
And here is my update view:
<?php echo form_open('kittens/update/')
echo form_hidden('id', $row[0]->id);
foreach($attributes as $field_name){
echo '<p>' . $field_name;
echo form_input($field_name, $row[0]->$field_name) . '</p>';
}
echo form_submit('', 'Update');
echo form_close();
?>
Any help would be appreciated! Not sure what specific part is giving me the trouble!
Use the following template:
Controller:
public function updateData(){
....
$data = array(
"columnName" => $columnValue
);
$whereValue = $someNumber;
$this->model_name->updateTable($data, $wherevalue);
...
}
Model:
public function updateTable($data, $whereValue){
$this->db->where('columnName', $whereValue);
$this->db->update('tableName', $data);
}
the first thing is that the model "MyModel" isn't loaded on the "edit" method in the controller.
If you're planning to use that specific model in every function of your controller you should load it in the constructor (so you don't have to load it every time).
Using$this->input->post('Name') in a model is a bad idea. You should receive that data in the controller process it (if you have to) and then send it to the method in the model.
I don't know if you can "chain" the db methods like this in codeigniter:
$this->db->where('id',$id)->update('table',$attributes);
try this:
$this->db->where('id',$id);
$this->db->update('table',$attributes);
Hope that helps
////////////model for update/////////////
public function update_customer_contacts($where, $data){
return $this->db->update('customer_contacts', $data, $where);
}
///////////////////update customer///////////////////
public function update_customer()
{
$data = array(
'company_name'=>$this->input->post('company_name'),
'address' =>$this->input->post('address'),
'telephone' =>$this->input->post('telephone'),
'fax' =>$this->input->post('fax'),
'email' =>$this->input->post('email'),
'website' =>$this->input->post('website'),
);
$res= $this->customer_model->update_customer(array('customer_id' => $this->input->post('customer_id')), $data);
;
echo json_encode($this->input->post());
}
I have a form set up in a controller that both loads the form and its previously populated contents from a database and processes the form as needed. The problem is $this->form_validation->run() never evaluates to FALSE, even if rules are not met.
Controller:
public function edit_version($node, $lang)
{
// load form validation class
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules("title|Title|required");
// run validation
if ($this->form_validation->run() !== FALSE)
{
// save input to database
die("validation successful");
}
else
{
// either validation was not passed or no data to validate
// load page edition view and display databse contents
// load page model
$this->load->model("page_model");
// get the page from database
$data["page"] = $this->page_model->get_page($node, $lang);
// load views
$this->load->view("admin/header.php", array("title" => "Edit page no.: $node, $lang version - Admin"));
$this->load->view("admin/pages/edit_page.php", $data);
$this->load->view("admin/footer.php");
}
}
Model:
class Page_model extends CI_Model
{
public function get_page($node, $lang)
{
// load the page
return $this->db->get_where("pages", array("node" => $node, "lang" => $lang))->row();
}
public function save_version($page)
{
$this->db->where("node", $page["node"]);
$this->db->where("lang", $page["lang"]);
$this->db->update("pages", $page);
}
public function search($query)
{
return $this->db->get_where("pages", $query)->result();
}
}
View:
<h2>Edit page</h2>
<?php
// load form helper
$this->load->helper("form");
// open a form
echo form_open("admin/page/{$page->node}/edit/{$page->lang}");
// print validation errors
echo validation_errors();
// title and content fields
echo form_label("Title: ", "title");
echo form_input("title", set_value("title", $page->title));
// aesthetic line break
echo "<br>";
echo form_label("Content: ", "content") . "<br>";
echo form_textarea("content", set_value("content", $page->content));
// save button and close form
echo form_submit("submit", "Save page");
echo form_close();
Thanks in advance.
syntax for setting rule is
$this->form_validation->set_rules('field_name', 'Label', 'rule1|rule2|rule3');
by considering rules your set rule line will be
$this->form_validation->set_rules('title','Title', 'required");
I'm not a CodeIgniter seasoned dev but from documentation is the proper syntax not the following?
$this->form_validation->set_rules("title","Title","required");
As per this link:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
Use
$this->form_validation->set_rules("title","Title","required");
instead of this
$this->form_validation->set_rules('title','Title','required');
I have tested this. It works like a Charm.
value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.