form validation as well as db error - php

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;

Related

PHP CodeIgniter: Login 404 Error 'Trying to get property 'email' of non-object'

I have recently starting following some coding tutorials for PHP CodeIgniter and I have run into a bit of a snag for my login and registration system. The registration works perfectly, accessing the database and creating accounts but there is a problem with my login code that I can not work my head around.
I receive the following error:
A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/Auth.php
Line Number: 23
Backtrace:
File: /opt/lampp/htdocs/application/controllers/Auth.php Line: 23
Function: _error_handler
File: /opt/lampp/htdocs/index.php Line: 315 Function: require_once
The code for the following is:
<?php
class Auth extends CI_Controller{
public function login()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
$password = md5($_POST['password']);
//check user in db
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username'=>$username, 'password'=>$password));
$query = $this->db->get();
$user = $query->row();
if ($user->email){
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
public function register()
{
if(isset($_POST['register'])) {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('password', 'Confirm Password', 'required|min_length[5]|matches[password]');
if($this->form_validation->run() == TRUE) {
//echo 'form validated';
//add user in database
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=> md5($_POST['password'])
);
$this->db->insert('users', $data);
$this->session->set_flashdata("success", "Your account has been registered");
redirect("auth/register", "refresh");
}
}
$this->load->view('register');
}
}
?>
Any help would be appreciated and if anymore code that I have used for this tutorial is needed for a solution, just let me know.
Thank you.
You will get that kindof error when the result object from the database is returning no rows hence an empty stdClass and thus you will not be able to access any properties. The correct way of doing this is to check that num_rows() is equal to 1 (e.g. there should only be one user with that name and password).
public function login() {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if ($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
/**
* Do not md5 your passwords!
* Use password_hash and password_verify!!
*/
$password = md5($_POST['password']); // DO NOT MD5 your passwords!
//check user in db
// this should be in a model!
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
if ($query->num_rows() == 1) {
$user = $query->row();
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
Generally you should get into the habit of checking if num_rows() > 0 before ever using result() row() .etc. because you can never be 100% sure that the data will be returned.
For example:
//model
function get_users() {
$query = $this->db->get('users');
if ($query->num_rows() == 0) {
return null;
}
return $query->result();
}
// controller
function something() {
$users = $this->model->get_users();
if (is_null($users)) {
exit('no users');
}
print_r($users);
}

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.

CodeIgniter callback function not displayed

I found other people with the same issue but couldn't find the solution to my problem. My error message is not displayed when the login fails if using the callback function.
loginController.php
public function validate_credentials () {
$this->load->model('users_model');
$query = $this->users_model->validate();
if($query)
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('/member/homes');
}
else
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_username_exists'); //test
$data['lofin_failed'] = 'Wrong usename or password'; // I added this line in the meantime to display an error message.
$this->load->view('header');
$this->load->view('navbar');
$this->load->view('loginForm', $data);
$this->load->view('footer');
}
}
public function check_username_exists()
{
$this->form_validation->set_message('check_username_exists', 'Wrong username or password!!');
return false;
}
users_model.php
public function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('game_players');
if($query -> num_rows() == 1) { // if we have one match
return true;
}
}
There is form validation rule :
is_unique[table.field]
that checks database if the username is unique, you don't need callback.
You can check it here https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
And you can use session flashdata instead of $data['lofin_failed']
you can check that here https://ellislab.com/codeigniter/user-guide/libraries/sessions.html
I found the problem. I simply forgot to add echo validation_errors(); at the beginning of the page....

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;
}
}
}
?>

Invalid Parameter Number. Parameter not defined

UPDATE2:
I've created a new WebUser.php component in /protected/components as follows:
<?php
class WebUser extends CWebUser{
private $_model;
function getId(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->id;
}
protected function loadUser($id=null){
if($this->_model===null)
{
if($id!==null)
{
$this->_model=Users::model()->findByPk($id);
}
return $this->_model;
}
}
}
I've registered the component in main.php as well. After uploading changes, my app still states that WebUser.getId is not defined.
UPDATE:
After making changes and then rolling them back, I'm getting a new error:
Property "CWebUser.getId" is not defined.
The snippet of code in question is:
$user = Users::model()->find('username=?', array(
Yii::app()->user->getId));
How and where should getId be set to reference the $id field in the Users model?
My UserController is throwing the following SQL Error:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number:
parameter was not defined. The SQL statement executed was: SELECT * FROM `users` `t` WHERE
username=? LIMIT 1
The error is being caused by this snippet of the controller:
public function actionProfile($id=''){
$user = Users::model()->find('username=?', array(Yii::app()->user->getId()));
if(!$id){
$id = $user->id;
if(!$id)
$this->redirect('login');
}
if( getUserSess('user_type') == 'Sitter') {
$this->render('profile_detail', array('user_id' => $id ));
} else {
$this->render('petowner_profile_detail',array(
'model'=>$this->loadModel($id),
));
}
}
The profile_detail view is as follows:
<?php
if(!$user_id){
$user_id = getUserSess('id');
}
$this->widget('ext.UserProfile.BasicProfile',array('user_id'=>$user_id)); ?>
<?php //$this->widget('ext.UserProfile.UserServices',array('user_id'=>$user_id)); ?>
The petowner_profile_detail view is as follows:
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'username',
'email',
'phone',
'fname',
'lname',
'address1',
'address2',
'city',
'state',
'zip',
'is_year_old',
'user_type',
// 'register_date',
// 'varified_date',
// 'is_premium',
// 'last_login',
),
)); ?>
How do I rectify he SQL error?
UPDATE:
$user = Users::model()->find('username=:id', array(":id" => Yii::app()->user->id));
UPDATE2:
Yii::app()->user->getId() or Yii::app()->user->id not Yii::app()->user->getId

Categories