Fetching data in codeigniter getting fatal error for dropdown - php

Fetching data in codeigniter getting fatal error for dropdown.
Fatal error: Call to undefined method Blogs_model::where() in C:\xampp\htdocs\project\admin\application\models\blogs_model.php on line 32
Blogs:
function add()
{
$data['categorylist']=$this->blogs_model->categories_dropdown();
$data['mainpage']='blogs';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
function addblogs()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('category_id','Category Name' , 'required');
$this->form_validation->set_rules('blog_title','Blog Title');
$this->form_validation->set_rules('description','Blog Description');
if($this->form_validation->run()== FALSE)
{
$data['categorylist']=$this->blogs_model->categories_dropdown();
$data['mainpage']='blogs';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> blogs_model -> insertblogs();
$this->flash->success('<h2>blogs Added Successfully!</h2>');
redirect('blogs');
}
}
Blogs_model
function categories_dropdown()
{
$this->table = 'category';
$this->where('status',1);
$categorylist=$this->dropdown('category_id','category_name');
return $categorylist;
}
View:
<div class="element">
<label for="categoryname"><font color="black">Category Name</font></label>
<?php
$categorylist['']='--Select Category Name--';
$category_id="id='category_id'";
if($this->input->post('category_id')) $selected=$this->input->post('category_id');else $selected='';
echo form_dropdown('category_id',$categorylist,$selected,$category_id);
?>
<?php echo form_error('category_id', '<div class="error">', '</div>'); ?><br/><br/>
</div>

Please update your model as follows.
function categories_dropdown()
{
$this->db->select('category_id','category_name');
$this->db->from('category');
$this->db->where('status',1);
$result = $this->db->get();
return $result->result();
}

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.

posts not showing after updating or creating codeigniter

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);

form validation as well as db error

I'm getting an error on form validation as well as db error. When I remove form validation the db query works perfectly fine. I have no idea what the error is and how to solve it.
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: libraries/Form_validation.php
Line Number: 953
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ` = 'admin' LIMIT 1' at line 2
SELECT * WHERE ` = 'admin' LIMIT 1
Filename: C:\wamp\www\myblog.com\system\database\DB_driver.php
Line Number: 330
[Controller: myblog]
class Myblog extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('blogmodel');
}
public function login()
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}
public function login_check()
{
$user=$this->input->post("username");
$pass=$this->input->post("password");
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run()==true)
{
$this->blogmodel->checklogin($user,$pass);
$this->load->view('header');
$this->load->view('logsuccess');
$this->load->view('footer');
}
else
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}
}
public function reg()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run()==true)
{
$user=$this->input->post("username");
$pass=$this->input->post("password");
$this->blogmodel->register($user,$pass);
$this->load->view('header');
$this->load->view('regsuccess');
$this->load->view('footer');
}
else
{
redirect('myblog/login');
}
}
[Model: blogmodel]
class Blogmodel extends CI_Model {
function __construct() {
parent::__construct();
}
function checklogin($user,$pass)
{
$this->db->select('username, password');
$this->db->from('user');
$this->db->where('username', $user);
$this->db->where('password', MD5($pass));
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result();
} else {
redirect('myblog/login');
}
}
function register($user,$pass)
{
$new_member=array(
'username' => $user,
'password' => md5($pass),
'status' =>1
);
$insert = $this->db->insert('user', $new_member);
return $insert;
}
[View:login]
echo "<h2>Register</h2>";
echo validation_errors();
echo form_open('myblog/reg');
echo form_label("Username: ");
echo form_input("username");
?><br/>
<?php
echo form_label("Password: ");
echo form_password("password");
?><br/>
<?php
echo form_label("Confirm Password: ");
echo form_password("password2");
?><br/>
<?php
echo form_submit("","Register");
echo form_close();
echo "<h2>Login</h2>";
echo validation_errors();
echo form_open('myblog/login_check');
echo form_label("Username: ");
echo form_input("username");
?><br/>
<?php
echo form_label("Password: ");
echo form_password("password");
?><br/>
<?php
echo form_submit("","Login");
echo form_close();
My guess is because you haven't set a table or row in your form validation.
Change this line, in your Controller;
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique');
to this;
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
As you'll see, I've added [users.username] to the is_inque rule. Without it, CI doesn't know what to compare it to.
The SQL Statement is missing the table and column to check
SELECT * FROM table WHERE column = 'admin' LIMIT 1
SQL syntax incorrect.
Your incomplete sql statement indicates that you want to fetch a COLUMN VALUE from a TABLE that contains the values of your Username.
So.include an appropriate Column name and table name,
Syntax:
Select * from table_name where column_name='admin' Limit 1;

undefined variable error in codeigniter model

I am working on a registration form
When i submit the form after the entering details the registration data get stored in the database but the the page shows the following error
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: dbRet
Filename: models/registration_model.php
Line Number: 47
I am not getting the prolem the same code is working good at the localhost but what is the problem at server??
This is the model Code
class Registration_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function index()
{
$data['page_title'] = 'Registration';
$this->load->view('client/general/head',$data);
$this->load->view('client/general/header');
$this->load->view('registration');
$this->load->view('client/general/footer');
}
function busregister()
{
$data['page_title'] = 'Registration';
$this->load->view('business/registration1');
}
public function save_registration($un,$email,$pwd,$utype)
{
try
{
$data = array(
'username' => $un,
'password' => $pwd,
'email' => $email
);
//print_r($data);
//die();
$this->load->database();
$this->db->reconnect();
if($utype=='buss')
{
$dbRet=$this->db->insert('business', $data);
}
else
{
$dbRet-$this->db->insert('user', $data);
}
if (!$dbRet) {
$ret['ErrorMessage'] = $this->db->_error_message();
$ret['ErrorNumber'] = $this->db->_error_number();
log_message('error', "DB Error: (".$ret['ErrorNumber'].") ".$ret['ErrorMessage']);
$this->db->close();
return $ret['ErrorNumber'];
}
else{
$rid=$this->db->insert_id();
$this->db->close();
return $rid;
}
}
catch (Exception $e){
return -1;
}
}
}?>
This is the controller code
class Registration extends CI_Controller {
public function index()
{
$this->load->helper(array('registration','date','country'));
$this->load->helper('client');
$this->load->model('Registration_model');
if ($this->input->post("submit_registration",TRUE))
{
if($this->form_validation->run("stud_registration_rules"))
{
$this->load->library(array('encrypt'));
$stud_first_name = $this->input->post('stud_user_name');
$stud_email = $this->input->post('stud_email');
$stud_pass = $this->input->post('stud_password');
$retval=$this->Registration_model->save_registration($stud_first_name,$stud_email,$this->encrypt->encode($stud_pass),"user");
var_dump($this->encrypt->encode($stud_pass));
if($retval!==-1){ //SAVE SUCCESS
$this->session->set_flashdata('flashSuccess', 'Record saved successfully.');
redirect('/');
}
else{
$this->session->set_flashdata('flashError', 'Error Saving Record');
redirect('/registration');
}
}
else{
// FORM IS NOT VALIDATED
$this->session->set_flashdata('flashError', 'Validation fields error');
redirect('/registration');
}
}
$this->Registration_model->index();
}
}
This is the view code
<div class="content">
<div class="container_12">
<div class="grid_12">
<?php if($this->session->flashdata('flashSuccess')) : ?>
<div class="alert alert-success">
×
<p><?php print_r($this->session->flashdata('flashSuccess'));
?></p>
</div>
<?php endif; ?>
<?php if($this->session->flashdata('flashError')) : ?>
<div class="alert alert-danger">
×
<p><?php print_r($this->session->flashdata('flashError'));
?></p>
</div>
<?php endif; ?>
<?php echo registration_form();?>
</div>
</div>
In your Model code Registration_model , Else part assignment operator is wrong
change the following line
$dbRet-$this->db->insert('user', $data);
to
$dbRet = $this->db->insert('user', $data);

getting memory allocation error in codeigniter HMVC

Description: I created simple login page with session and mysql database using PHP,MySQL Database,CodeIgniter(HMVC) and XAMPP Server in local system.
Problem: I am getting following error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in C:\xampp\htdocs\ci\application\third_party\MX\Modules.php on line 114.
Question: Please tell me the solution how to resolve this above error.
View:
*login2.php*
<?php echo form_open(/* base_url(). */'user/user/login'); ?>
<?php
if ($this->session->flashdata('login_error')) {
echo 'you have entered an incorrect username or password';
}
echo validation_errors();
?>
<label>UserName</label>
<div>
<?php echo form_input(array('id' => 'username', 'name' => 'username', 'placeholder' => 'Enter ur name')); ?>
</div>
<label>Password</label>
<div>
<?php echo form_password(array('id' => 'password', 'name' => 'password', 'placeholder' => 'Enter ur password')); ?>
</div>
<div>
<?php echo form_submit(array('name' => 'submit'), 'Login'); ?>
</div>
<?php echo form_close(); ?>
Controller:
*user.php*
<?php
class User extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$this->login();
}
function main_page() {
echo 'You are logged in';
}
function login() {
$this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[200]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login2');
} else { // process their input and login the user
extract($_POST);
$user_id = $this->user->login($username, $password);
if ($user_id) {
//login failed error...
$this->session->set_flashdata('login_error', TRUE);
redirect('user/login');
} else {
//logem in
$this->session->set_userdata(array(
'logged_in' => TRUE,
'user_id' => $user_id
));
redirect('user/main_page');
}
}
}
}
?>
Model:
*user.php*
<?php
Class User extends CI_Model {
function login($username, $password) {
$this->db->select('id, username, password');
$this->db->from('users');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>

Categories