posts not showing after updating or creating codeigniter - php

My question is why posts are not showing after updating or creating in codeigniter? for example if I create a post without assigning a category in the select html tag it creates the post in the database but is not showing in the application and same if update the post without select a category in select html tag. But if I assign a category it shows the post.
Here is my code
Model category
public function pelicula_categoria()
{
$this->db->order_by('categoria_nombre');
$query = $this->db->get('categorias');
return $query->result_array();
}
Model post
public function listar_peliculas()
{
$this->db->select();
$this->db->join('categorias', 'categorias.categoria_id = peliculas.categoria_id');
$this->db->from('peliculas');
$this->db->order_by('peliculas.pelicula_id', 'desc');
$query = $this->db->get();
return $query->result_array();
}
Controller add post
public function agregar_pelicula()
{
$data['error'] = null;
$data['titulo_agregar'] = 'Agregar pelicula';
$data['categorias'] = $this->Categorias_Model->pelicula_categoria();
if ($this->input->post())
{
$this->form_validation->set_rules('pelicula_titulo', 'Titulo', ` 'required');
$this->form_validation->set_rules('pelicula_sinopsis', 'Sinopsis', 'required');
$this->form_validation->set_rules('pelicula_caratula', 'Caratula', 'required');
$this->form_validation->set_rules('pelicula_estreno', 'Estreno', 'required');
$this->form_validation->set_rules('pelicula_puntuacion', 'Puntuacion', 'required');
$this->form_validation->set_rules('pelicula_director', 'Director', 'required');
$this->form_validation->set_rules('pelicula_duracion', 'Duracion', 'required');
$this->form_validation->set_rules('pelicula_pais', '', 'required');
$this->form_validation->set_rules('categoria_id', 'Categoria', 'required');
$this->form_validation->set_rules('pelicula_enlace', 'Enlace', 'required');
if ($this->form_validation->run() == FALSE)
{
$data['error'] = "Todos los campos son requeridos";
}
else
{
$this->Peliculas_Model->insert_pelicula();
$this->session->set_flashdata('mensaje', 'Pelicula agregada correctamente');
redirect(base_url() . 'admin');
}
}
$this->load->view('admin/layouts/header', $data);
$this->load->view('admin/modules/create', $data);
$this->load->view('admin/layouts/footer');
}
And finally showing the categories from database in create view and update view
<select class="custom-select" name="categoria_id">
<option selected>Categoria</option>
<?php foreach ($categorias as $categoria): ?>
<option value="<?php echo $categoria['categoria_id']; ?>">
<?php echo $categoria['categoria_nombre']; ?>
</option>
<?php endforeach; ?>
</select>

Did you check in print_r(); function?
//example - Model
public function userlists()
{
$data = '';
$sql = "SELECT * FROM customer";
$query = $this->db->query($sql);
if($query->num_rows()>0)
{
return $query->result_array();
}
}
//Controller
$data['userlist']= $userslists=$this->example_model->userlists();
//check the array values is exists or not, just print the variable
print_r($userslists);

Related

404 Page Not Found in Codeigniter

I am new to CodeIgniter and experiencing the following error after creating new model for the purpose of user dashboard in addition to admin dashbaord. It is really great if some one can help me. I checked previous answers in the StackOverflow but none helped me.
I am experiencing following error.
Code segment relevant to the error is as follows.
Model code
<?php
//Details of queries whicha re used to interact with teh database
class Queries extends CI_Model {
//Created a function with the name getRoles
public function getRoles() {
//Fetch the reocrds from the table
$roles = $this->db->get('tbl_roles');
if ($roles->num_rows() > 0) {
return $roles->result();
}
}
//Created a function with the name getColleges
//Used to list collge names in addcodmin view page
public function getColleges() {
//Fetch the reocrds from the table
$colleges = $this->db->get('tbl_college');
if ($colleges->num_rows() > 0) {
return $colleges->result();
}
}
public function registerAdmin($data) {
return $this->db->insert('tbl_users', $data);
}
//create function to check whther three is a admin or not...if not only
// that add admin button will be appered
public function checkAdminExist() {
$checkAdmin = $this->db->where(['role_id' => '1'])->get('tbl_users');
if ($checkAdmin->num_rows() > 0) {
return $checkAdmin->num_rows();
}
}
//Create function to check the entered email and password existance
public function adminExist($email, $password) {
$checkAdmin = $this->db->where(['email' => $email, 'password' => $password])->get('tbl_users');
if ($checkAdmin->num_rows() > 0) {
return $checkAdmin->row();
}
}
//Created function makeCollege and return value and
public function makeCollege($data) {
//if value is 0 - and 1 - if the data get inserted into the table
return $this->db->insert('tbl_college', $data);
}
//Created function register coadmin fot coadmin query called and passing data to the admin.php
//used insert method of the db class if inserted value 1 and if not value 0
public function registerCoadmin($data) {
return $this->db->insert('tbl_users', $data);
}
//qruery to display all the colleges and details in teh dashboard
public function viewAllColleges() {
//get data from differendt table and view them in one single table
$this->db->select(['tbl_users.user_id', 'tbl_users.email', 'tbl_college.college_id',
'tbl_users.username', 'tbl_users.gender', 'tbl_college.collegename',
'tbl_college.branch', 'tbl_roles.rolename']);
$this->db->from('tbl_college');
$this->db->join('tbl_users', 'tbl_users.college_id = tbl_college.college_id');
$this->db->join('tbl_roles', 'tbl_roles.role_id = tbl_users.role_id');
//get the details and return details
$users = $this->db->get();
return $users->result();
}
public function insertStudent($data) {
return $this->db->insert('tbl_student', $data);
}
public function getStudents($college_id) {
//select fields required to diaply from the college and the student table
$this->db->select(['tbl_student.id', 'tbl_college.collegename', 'tbl_student.studentname',
'tbl_student.gender', 'tbl_student.email', 'tbl_student.course']);
//Common fileds in the both the table
$this->db->from('tbl_student');
$this->db->join('tbl_college', 'tbl_college.college_id = tbl_student.college_id');
//Take only stuednts who has college id (Get the details of all the students with the college id of 3)
$this->db->where(['tbl_student.college_id' => $college_id]);
$students = $this->db->get();
return $students->result();
}
public function getStudentRecord($id) {
$this->db->select(['tbl_college.college_id', 'tbl_college.collegename',
'tbl_student.id', 'tbl_student.email', 'tbl_student.gender', 'tbl_student.studentname',
'tbl_student.course']);
$this->db->from('tbl_student');
$this->db->join('tbl_college', 'tbl_college.college_id = tbl_student.college_id');
$this->db->where(['tbl_student.id' => $id]);
$student = $this->db->get();
return $student->row();
}
public function upgradeStudent($data, $id) {
return $this->db->where('id', $id)
->update('tbl_student', $data);
}
public function removeStudent($id) {
return $this->db->delete('tbl_student', ['id' => $id]);
}
}
?>
Controller code 1
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends MY_Controller {
public function dashbaord() {
$this->load->model('queries');
//$college_id=$this->session->userdata('college_id';
$students = $this->queries->getStudents($college_id);
$this->load->view('users',['students'=>$students]);
}
}
Controller code 2
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends MY_Controller {
public function index() {
//New function to display add admin button
//and commented the existing code of $this->load->view('home');
$this->load->model('queries');
$checkAdminExist = $this->queries->checkAdminExist();
$this->load->view('home', ['checkAdminExist' => $checkAdminExist]);
//
}
public function adminRegister() {
//loading teh queries model
$this->load->model('queries');
//Calling the getRoles function inside the roles
//$roles holds the data of 2 records availble in the roles table
$roles = $this->queries->getRoles();
// print_r($roles);
// exit();
// $this->load->view('register');
//Pass this to an register view in type of an array and pass the data to register view
$this->load->view('register', ['roles' => $roles]);
}
public function adminSignup() {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('role_id', 'Role', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('confpwd', 'Password Again', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run()) {
$data = $this->input->post();
$data['password'] = sha1($this->input->post('password'));
$data['confpwd'] = sha1($this->input->post('confpwd'));
$this->load->model('queries');
if ($this->queries->registerAdmin($data)) {
$this->session->set_flashdata('message', 'Admin Registered Sucessfully');
return redirect("welcome/adminRegister");
} else {
$this->session->set_flashdata('message', 'Failed to Register Admin!');
return redirect("welcome/adminRegister");
}
// echo '<pre>';
// print_r($data);
// echo '<pre>';
// exit();
} else {
echo $this->adminRegister();
}
}
//Create new view for login function in teh welcome controllder
public function login() {
//restrict the acess of the login page of welcome controller
if ($this->session->userdata("user_id"))
//redirecting to the dash board page
return redirect("admin/dashboard");
//End
$this->load->view('login');
}
public function Signin() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run()) {
$email = $this->input->post('email');
$password = sha1($this->input->post('password'));
$this->load->model('queries');
$userExist = $this->queries->adminExist($email, $password);
echo '<pre>';
print_r($userExist);
echo '<pre>';
//information saved in the session data will be accesed when teh user loged into the system
//inside if the yser id exists user details will be stored inside the session
if ($userExist) {
if ($userExist->user_id == '1') {
$sessionData = [
'user_id' => $userExist->user_id,
'username' => $userExist->username,
'email' => $userExist->email,
'role_id' => $userExist->role_id,
];
//redirect to teh dash board upon giving teh correct user id and password
//settin user data to the dashboard
$this->session->set_userdata($sessionData);
return redirect("admin/dashboard");
//if the coadmin login session creatiion whos id is grater than 1
} else if ($userExist->user_id > '1') {
$sessionData = [
'user_id' => $userExist->user_id,
'username' => $userExist->username,
'email' => $userExist->email,
//'college_id' => $userExist->college_id,
'role_id' => $userExist->role_id,
];
//redirect to teh dash board upon giving teh correct user id and password
//settin user data to the dashboard
$this->session->set_userdata($sessionData);
return redirect("users/dashboard");
}
} else {
$this->session->set_flashdata('message', 'Email or password is incorrect');
return redirect("welcome/login");
}
} else {
$this->login();
}
}
//crerate logout function for the user to logout
public function logout() {
//closing teh session inside logout function usinhg the userid
$this->session->unset_userdata("user_id");
return redirect("welcome/login");
}
}
View
<?php include("inc/header.php"); ?>
<div class="container">
<h3>COADMIN DASHBOARD</h3>
<?php
// echo $username = $this->session->userdata('username');
$username = $this->session->userdata('username');
?>
<h5>Welcome <?php echo $username; ?></h5>
<hr>
<div class="row">
<table class="table table-hover">
<thead>
<th scope="col">ID</th>
<th scope="col">Student Name</th>
<th scope="col">College Name</th>
<th scope="col">Email</th>
<th scope="col">Gender</th>
<th scope="col">Course</th>
</thead>
<tbody>
<!-- if users contain the data-->
<?php //if (count($students)): ?>
<!-- Iterate the array to show he records-->
<?php //foreach ($$students as $student): ?>
<tr class="table-active">
<td><?php //echo $student->id; ?></td>
<td><?php //echo $student->studentname; ?></td>
<td><?php //echo $student->collegename; ?></td>
<td><?php //echo $student->email; ?></td>
<td><?php //echo $student->gender; ?></td>
<td><?php //echo $student->course; ?></td>
</tr>
<?php //endforeach; ?>
<?php //else: ?>
<!-- If count is 0 table will not display any data-->
<tr>
<td>No records found!</td>
</tr>
<?php //endif; ?>
</tbody>
</table>
</div>
</div>
<?php include("inc/footer.php"); ?>
Any help will be highly appreciated. Thanks in advance.

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')),
// ...

validation error in Codeigniter

May I know why my insert function will display the validation message first even i do not insert any data yet.once I enter the insert page,it display the validation message.i have try to move the form validation to the below of the if else statement,it do not show the validation message but it cannot submit the data to the database. below is my controller function.
public function Insert_Result($Course_ID=null)
{
$this-load-helper('form');
$this-load-library('form_validation');
/* Model */
$this-load-model('ResultEvaluation');
/* Session */
$session_data = $this-session-userdata('logged_in');
$data['Ins_ID'] = $session_data['Ins_ID'];
$this-session-set_userdata($data);
/* Form Validation*/
//$this-form_validation-set_rules('Course_ID', 'Course_ID', 'required');
$this-form_validation-set_rules('Matric_No', 'Matric_No','required');
$this-form_validation-set_rules('Student_Name', 'Student_Name', 'required');
$this-form_validation-set_rules('Result_Mark_1', 'Result_Mark_1', 'required');
$this-form_validation-set_rules('Result_Mark_2', 'Result_Mark_2', 'required');
$this-form_validation-set_rules('Result_Mark_3', 'Result_Mark_3', 'required');
$this-form_validation-set_rules('Result_Mark_4', 'Result_Mark_4', 'required');
$this-form_validation-set_rules('Result_Mark_5', 'Result_Mark_5', 'required');
if ($this-form_validation-run() === FALSE)
{
$data['results'] = $this-ResultEvaluation-get_record();
$data['query'] = $this-ResultEvaluation-view($Course_ID);
$this-load-view('templates/header');
$this-load-view('Insert_Result', $data);
$this-load-view('templates/footer');
}
else
{
$my_action = $this-input-post('submit');
if ($my_action == 'Submit')
{
$this-ResultEvaluation-insert_record($Course_ID);
redirect('Result_Evaluation/Student_Result_List/'.$Course_ID,
'refresh');
}
}
$my_action = $this-input-post('submit');
if ($my_action == 'Cancel')
{
redirect('Result_Evaluation/Student_Result_List/'.$Course_ID,
'refresh');
}
}
I think this should help
public function index(){
$this->load->library(array('form_validation'));
$this->form_validation->set_rules('field_name', 'Text','trim|required');
if($this->form_validation->run()==TRUE){
// do something
}else{
// validation error
redirect("to/your/controller");
break;
}
}
for more information visit : http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Why adding $this->models. make it faster?

I was playing around with this code. http://programmersvoice.com/tag/code
And I noticed that the following line.
$this->load->model($this->models."pagemodel", 'pages');
I compare this with
$this->load->model("pagemodel", 'pages');
This is what codeigniter's document http://codeigniter.com/user_guide/general/models.html#loading suggest.
However method 2 takes longer time than the first one.
Could anyone explain what "$this->models." do please?
Thanks in advance.
The following is the whole code of pages.php in controllers/admin
<?php
class Pages extends Application
{
function Pages()
{
parent::Application();
$this->auth->restrict('editor'); // restrict this controller to editor and above
$this->load->model($this->models."pagemodel", 'pages'); // Load the page model
}
function manage()
{
$data = $this->pages->pages(); // List the pages
$this->table->set_heading('Title', 'Slug', 'Actions'); // Setting headings for the table
foreach($data as $value => $key)
{
$actions = anchor("admin/pages/edit/".$key['id']."/", "Edit") . anchor("admin/pages/delete/".$key['id']."/", "Delete"); // Build actions links
$this->table->add_row($key['title'], $key['slug'], $actions); // Adding row to table
}
$this->auth->view('pages/manage'); // Load the view
}
function delete($id)
{
$this->pages->delete($id);
$this->auth->view('pages/delete_success');
}
function add()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$this->auth->view('pages/add');
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->add($data);
$this->auth->view('pages/add_success');
}
}
function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$data = $this->pages->page($id);
$this->auth->view('pages/edit', $data[0]);
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->edit($id, $data);
$this->auth->view('pages/edit_success');
}
}
}
?>
I'm not totally sure about the following, since the current version of Codeigniter doesn't seem to populate the $this->models variable, but I think that:
$this->models contained the full path to the application models directory, and therefore loading is faster, since CI doesn't have to look in different folders (global & application)

Categories