Add data to the database using codeigniter - php

I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}

If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).

Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}

Related

How to compare form input data to database data in a custom codeigniter form validator?

Edit: Some naming had been mixed up in my attempts to solve it myself. I've fixed the callback etc naming and the same error persists.
I am attempting to create a login page for my codeigniter website. I already have a registration page that correctly inputs usernames and passwords in to a "users" table. I am having issues understanding the syntax of creating the functions needed for custom form validators.
My error is "Unable to access an error message corresponding to your field name" for the password and username custom validators.
Here is the relevant part of the controller "login_ctrl"
class login_ctrl extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('login_mdl');
}
function index() {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_userCorrect');
//Validating Password Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_passwordCorrect');
//variables to pass form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//reload login page if validation fails
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
//functions for custom validation
function userCorrect($username) {
$this->load->library('form_validation');
//the loads the model that contains the function to compare input to database data
$userExists = $this->login_mdl->userExists($username);
if ($userExists) {
$this->form_validation->set_message(
'userCorrect', 'correct user.'
);
return true;
} else {
$this->form_validation->set_message(
'userCorrect', 'not a valid user name.'
);
return false;
}
}
function passwordCorrect($password) {
$this->load->library('form_validation');
$passwordExists = $this->login_mdl->passwordCorrect($password);
if ($passwordExists) {
$this->form_validation->set_message('passwordCorrect', 'correct password.');
return true;
} else {
$this->form_validation->set_message('passwordCorrect', 'invalid password.');
return false;
}
}
This is the corresponding view "login"
<?php echo form_open('login_ctrl'); ?>
<h1>Login</h1><hr/>
<?php if (isset($message)) { ?>
<?php } ?>
<?php echo form_label('User Name :'); ?> <?php echo form_error('username'); ?><br />
<?php echo form_input(array('id' => 'username', 'name' => 'username')); ?><br />
<?php echo form_label('Password :'); ?> <?php echo form_error('password'); ?><br />
<?php echo form_input(array('id' => 'password', 'name' => 'password')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
Finally, this is the corresponding model "login_mdl" (I think the issue might be in this guy).
<?php
class login_mdl extends CI_Model{
function __construct() {
parent::__construct();
}
function userExists($username) {
$this->db->select('id');
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
function passwordCorrect($password) {
$this->db->select('password');
$this->db->where('username', $username);
$query = $this->db->get('users');
$result = $query->row();
return $result->password;
if ('password' == $password) {
return true;
} else {
return false;
}
}
}
?>
I think my issue is related to the db calls and if statements but I've been reading documentation and failing at fixing this for hours so a new pair of eyes would be greatly appreciated.
You need to make your fieldname on your costume rules function is same as your function callback. So, it’s should be like this :
$this->form_validation->set_message(
'userCorrect', 'correct user.'
Do same thing on your other function.

converting submitted form data in codeigniter using inflector helper

I have a codeigniter form which runs some basic validation and submits data to the database. But I want to additionally alter the post data of one of the fields to use the inflector helper in order to convert the posted data to camel case before submitting to the database. How do I do this?
Here is my current form:
<?php echo form_open('instances/create') ?>
<label for="content">Content</label>
<textarea name="content"></textarea><br />
<input type="submit" name="submit" value="Create" />
</form>
Here is my current controller:
public function create(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('inflector');
$data['title'] = 'Create an instance';
$this->form_validation->set_rules('title', 'Title', 'required');
//want to camelize the 'title' here
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('instances/create');
$this->load->view('templates/footer');
}
else
{
$this->instances_model->set_instances();
$this->load->view('instances/success');
}
}
and here's my model:
<?php
class Instances_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function get_instances($slug = FALSE){
if ($slug === FALSE){
$query = $this->db->get('extra_instances');
return $query->result_array();
}
$query = $this->db->get_where('extra_instances', array('slug' => $slug));
return $query->row_array();
}
public function set_instances(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'slug' => $slug,
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'year' => $this->input->post('year'),
'credit' => $this->input->post('credit'),
'source' => $this->input->post('source')
);
return $this->db->insert('extra_instances', $data);
}
}
I know that you can camelize a variable with the following:
echo camelize('my_dog_spot'); // Prints 'myDogSpot'
and I know that you can run custom validation like this:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
But I'm lacking the knowledge of how to put this altogether to quickly change the POST data before submitting to the database.
Nothing too complicated, you can do it after you pass the validation, just before inserting your data array into the database:
$data = array(
'slug' => $slug,
'title' => camelize($this->input->post('title')),
// ...

CodeIgniter: 404 Page Not Found ( In Hosting Server )

note : everything going well when I try in Localhost.
So I have a problem when I want to call my do_login controller in my login form.
this is my controller :
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Do_login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('login_model', '', TRUE);
}
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login_view');
}
else
{
redirect('home', 'refresh');
}
}
public function check_database($password)
{
$email = $this->input->post('email', TRUE);
$result = $this->login_model->check_login($email, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'user_id' => $row->user_id,
'email' => $row->email
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Email / Password salah');
return FALSE;
}
}
}
?>
this is my view :
<?php
$attributes = array('class' => 'form-signin', 'id' => 'myform');
echo form_open('do_login', $attributes);
?>
When I try it in Localhost, everything going well and smooth.
But when I try in my web server, everytime I submit the login form, I directed into 404.
Thanks for your help :)
Check your file names Because it happens with me that different case file name was worked on localhost but not on server.
So check it once.

CodeIgniter + Wamp: Unable to locate the file error

I just installed a fresh installation of Wamp server and copied a working CodeIgniter project(not done by me) into it. I have changed the settings in config.php(base_url) and database.php(mysql credentials) and am sure that the database connection is ok.
i can see the login page but when i login, it returns me the "unable to locate the file error", i believe its some settings on the Wamp server i need to do. there is no .htaccess file in the root CI folder, should there be? any suggestions what might went wrong?
in the controllers folder there is an admin.php file
<?php
class Admin extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->lang->load($this->config->item('admin_language'), $this->config->item('admin_language'));
}
private $rules = array(
array(
'field' => 'username',
'label' => 'lang:username',
'rules' => 'trim|required',
),
array(
'field' => 'password',
'label' => 'lang:password',
'rules' => 'trim|required|min_length[8]',
)
);
function index()
{
$this->load->library('form_validation');
$redirect_to = $this->config->item('base_url') . 'index.php/admin/products/';
if ($this->auth->logged_in() == FALSE)
{
$data['error'] = FALSE;
$this->load->library('form_validation');
$this->form_validation->set_rules($this->rules);
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
//echo "1";die;
if ($this->form_validation->run() == FALSE)
{
//echo "if";die;
$this->load->view('admin/login', $data);
}
else
{
//echo "el";die;
$this->auth->login($this->input->post('username'), $this->input->post('password'), $redirect_to, 'index.php/admin/login');
}
}
else
{
//echo "asdadad";die;
redirect($redirect_to);
}
}
function logout()
{
$this->auth->logout($this->config->item('base_url') . 'index.php/admin');
}
}
?>
Please change you function name index to login.
If you are using function name index then url will we localhost/projectname/index.php/admin
If you change function name to login then this will we work.

Codeigniter user functionality

im working on a project at the moment that allows users to register and log into there own user area and add/edit/delete note snippets.
Im currently working on the edit class and im wondering how can i make it so that other users cant visit the same url and edit someones note? (all notes are stored in the same table in the database)
schema = id, title, description, snippet, user_id
for example if user1 wants to edit his note at http://domain.com/edit/1 (which is bound to his user_id in the database) how can i stop user2 from visiting that same url and editing his note?
here is the controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Mysnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['private_snippets'] = $this->dashboard_model->private_snippets();
$this->load->view('dashboard/my_snippets', $this->data);
}
function edit_snippet($snippet_id) {
$snippet = $this->dashboard_model->get_snippet($snippet_id);
//validate form input
$this->form_validation->set_rules('title', 'Title', 'required');
if (isset($_POST) && !empty($_POST))
{
$data = array(
'title' => $this->input->post('title'),
);
if ($this->form_validation->run() === true)
{
$this->dashboard_model->update_snippet($snippet_id, $data);
$this->session->set_flashdata('message', "<p>Product updated successfully.</p>");
redirect(base_url().'mysnippets/edit_snippet/'.$snippet_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['snippet'] = $snippet;
//display the edit product form
$this->data['title'] = array(
'name' => 'title',
'type' => 'text',
'value' => $this->form_validation->set_value('title', $snippet['title']),
);
$this->load->view('dashboard/edit_snippet', $this->data);
}
}
heres the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
$query = $this->db->get('snippets');
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
}
heres the view:
<?php echo $message;?>
<?php $snippet_id = $snippet['id']; ?>
<?php echo form_open("mysnippets/edit_snippet/$snippet_id");?>
<?php echo form_input($title); ?>
<?php echo form_submit('submit', 'Submit');?>
<?php echo form_close(); ?>
is there a way i can restrict it so if another user tried to go to that url i can redirect them or show a error message
Something like this might work.
public function edit_snippet(snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
// this depends on what you are using for sessions;
// recommend you use db sessions
if($snippet->user_id != $this->session->userdata('user_id');)
{
redirect('/mysnippets');
}
else
{
//allow editing
You could check whether the id you are editing is the same as the session id provided when you have logged in.
it could be something like :
if ($snippet_id != $this->session->userdata('login_id'))
{
//redirect to another page
}
I would just add a line to the following function in the model:
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
//users can access only their own snippets
$this->db->where('user_id', $this->session->userdata('user_id'));
$query = $this->db->get('snippets');
return $query->row_array();
}
That prevents them from accessing the information, but I'd do something to prevent them from even being able to try in the first place, i.e. not giving them the choice.

Categories