I am new to php framework i have created a simple form and want to inserts its value in database but failed to do so don't know where i am wrong!!!
Every time i am getting MySQL returned an empty result set (i.e. zero rows).
i am using CodeIgniter 3 and mysqli drivers this is my Controller
<?php
//display_errors(on);
error_reporting(E_ALL);
class Register extends CI_Controller {
public function index () {
//Validations
$rules=array (
"username"=> array(
"field"=>"username",
"label"=>"Username",
"rules"=>"required|max_length[20]|min_length[5]|callback_username_is_taken"
),
"password"=> array(
"field"=>"password",
"label"=>"Password",
"rules"=>"required|max_length[20]|min_length[6]"
),
"pass_conf"=> array(
"field"=>"pass_conf",
"label"=>"Password",
"rules"=>"required|matches[password]"
),
"email"=> array(
"field"=>"email",
"label"=>"Email",
"rules"=>"required|valid_email|callback_is_taken"
)
);
//set the rules
$this->form_validation->set_rules($rules);
//Override the message
$this->form_validation->set_message('required','The %s field is empty');
// check to see if form has been submitted
if ($this->form_validation->run()!=true) {
$this->load->helper('url');
$this->load->view('register'); //Display page
$this->load->view('footer');
}else {
echo "Donkey Butt";
$form=array();
$form['username']=$this->input->post("username");
$form['password']=md5($this->input->post("password"));
$form['email']=$this->input->post("email");
if(self::createUser($form['username'],$form['password'],$form['email'])==true) {
//Created User Successfully
echo "Success";
//$this->load->view("success",$data);
}else{
echo "problem in subbmitting the form";
}
}
}
public function username_is_taken($input) {
$query="SELECT * FROM `tbl_usrs` WHERE `username`=? ";
$arg=array ($input);
$exec=$this->db->query($query,$arg) or die(mysqli_error());
echo $query;
if($exec->num_rows() >0)
{
$this->form_validation->set_message('username_is_taken','Sorry the UserName <b> $input </b> is already taken');
return false;
}else {
return true;
}
}
public function email_is_taken($input) {
$query="SELECT * FROM `tbl_usrs` WHERE `email`=? ";
$arg=array ($input);
$exec=$this->db->query($query,$arg) or die(mysqli_error());
echo $query;
if($exec->num_rows() >0)
{
$this->form_validation->set_message('email_is_taken','Sorry the email <b> $input </b> is already taken');
return false;
}else {
return true;
}
}
public function createUser($user,$pass,$email)
{
$query="
INSERT INTO `tbl_usrs` (`username`,`password`,`email`,`ip`)
VALUES (?,?,?,?)
";
$arg=array (self::protect($user),self::protect($password),$email,$_SERVER['REMOTE_ADDR']);
if($this->db->query($query,$arg)==true)
{
echo $query;
return true; // if added to database
}else {
return false;
}
}
public function protect($str) {
return mysqli_real_escape_string($str);
}
}
?>
fixing mysqli_real_escape_string($str); //excepts two parameters only one given
fixing is this make your code work
Related
I try to make an alert for invalid login so I use
$this->session->set_flashdata('error', 'Invalid Credentials');
redirect("admin/login");
and i put this in my index function
$data=[];
if (isset($_SESSION['error'])) {
$data['error']=$_SESSION['error'];
}else{
$data['error']="NO_ERROR";
}
//$this->load->helper('url');
$this->load->view('adminpanel/loginview',$data);
but when i reload my login page, the alert was already execute, can anyone help me with this?
this is my full controller
public function index()
{
$data=[];
if (isset($_SESSION['error'])) {
$data['error']=$_SESSION['error'];
}else{
$data['error']="NO_ERROR";
}
//$this->load->helper('url');
$this->load->view('adminpanel/loginview',$data);
}
function login_post(){
//$this->load->helper('url'); set at autoload file
// print_r($_POST); test the post result
if (isset($_POST)) {
$email=$_POST['email'];
$password=$_POST['password'];
$query = $this->db->query("SELECT * FROM `backenduser` WHERE `username`='$email' AND `password`='$password'");
if ($query->num_rows()) {
// credential are valid
$result = $query->result_array();
//echo "<pre>";
//print_r($result); die();
$this->session->set_userdata('user_id', $result[0]['uid']);
redirect('admin/dashboard');
}
else{
//invalid credentials
$this->session->set_flashdata('error', 'Invalid Credentials');
redirect("admin/login");
}
}
else{
die("Invalid Input!");
}
}
function logout(){
session_destroy();
}
}
Your problem is here:
if (isset($_POST)) {
...
}
This will always return true because $_POST is always available, so it will always show the alert. You can check if the request is post or not by:
if(count($_POST) > 0){
...
}
also use this
if(!empty($_POST)){
...
}
Controller code
How to check email already exist in multiple table in codeigniter
function rolekey_exists($key) {
$this->Register_model->mail_exists($key);
}
Model code
Below shown in the model code i joined two table how to check email already exist before inserting in two different table
function mail_exists($key)
{
$this->db->select('*');
$this->db->from('supplier_registration');
$this->db->join('customer_registration', 'supplier_registration.email = customer_registration.email');
$this->db->where('supplier_registration.email',$key);
$query=$this->db->get();
if ($query->num_rows() > 0){
return true;
}
else {
return false;
}
}
You can use OR condition to check email in multiple tables.
$this->db->select(*);
$this->db->->from('supplier_registration, customer_registration');
$this->db->where('supplier_registration.email',$key);
$this->db->or_where('customer_registration.email',$key);
Hope this will help you.
Change your TRUE and FALSE as well check in controller
In Model
function mail_exists($key)
{
$this->db->select('*');
$this->db->from('supplier_registration');
$this->db->join('customer_registration', 'supplier_registration.email = customer_registration.email');
$this->db->where('supplier_registration.email',$key);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
# email exist
return false;
}
else {
# new/fresh email
return true;
}
}
In Controller
function rolekey_exists($key) {
$result = $this->Register_model->mail_exists($key);
if ($result == TRUE) {
echo "Email Exists";
} else {
echo "New Email";
}
}
This is my callback function, I want to check the database for duplicate value, I have tried a lot, but I can't get validation to work. I'm new to Codeigniter so any help would be appreciated!
public function alias_exist_check()
{
$scol_code = $this->input->post('school_code');
$user_id=$this->input->post('user_id');
$query=$this->db->get_where('user_application',array('school_code'=>$scol_code, 'user_id'=>$user_id));
$row= $query->row_array();
if(!$row['user_id']==$user_id && !$row['school_code']==$scol_code)
{
return TRUE;
} else {
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
return FALSE;
}
}
UPDATE1 ::
i tried this but its not working me help me if i wrote any mistakes.
$this->form_validation->set_rules('school_code', 'School Name','required','callback_alias_exist_check', 'trim|xss_clean'); $where = array(
'school_code' => $this->input->post('school_code'),
'user_id' => $this->input->post('post'));
if( ! $this->lawschool_model->alias_exist_check($where))
{
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
}
if ($this->form_validation->run() == FALSE)
{
$data['row']= $this->lawschool_model->Getuser($data1);
$data['row1']= $this->lawschool_model->GetData1();
$this->ag_auth->view('Home',$data);
}
else
{
$insert = $this->db->insert('user_application',$data);
if($insert==TRUE)
{
/*$idNum = $this->input->post('school_code');
$data1 = $this->lawschool_model->upddata_school();*/
$data['row'] = $this->lawschool_model->Getuser($data1);
$data['row1'] = $this->lawschool_model->GetData1();
$this->ag_auth->view('Home',$data);
}
}
UPDATE2::finaly its works fine,here is my working code
$this->form_validation->set_rules('school_code', 'School Name','required','callback_alias_exist_check1', 'trim|xss_clean');
function alias_exist_check1($scol_code,$user_id)
{
$sql = "SELECT * FROM user_application WHERE school_code = ? AND user_id = ?";
$val = $this->db->query($sql,array($scol_code ,$user_id ));
if ($val->num_rows)
{
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
return TRUE;
}
else
{
return FALSE;
}
}
Model
public function alias_exist($where)
{
return $this->db->where($where)->count_all_results('user_application') > 0;
}
Controller
public function alias_exist_check()
{
$where = array(
'school_code' => $this->input->post('school_code'),
'user_id' => $this->input->post('user_id')
);
return ! $this->name_model->alias_exist($where);
}
The first function was not working because you tried to access post data from within the callback itself. This does not appear to work well with callbacks. This is because codeigniter will remove all post data from the request as soon as your run the form validator run method. It repopulates post data only when form processing is complete. Pass any extra parameters you need for you callback functions to work like this
callback_foo[bar]
I don't know why this don't work at all. I maybe wrong with my understanding that is why.
here is the situation.
MVC pattern
form validation stuffs
Here are the codes
public function userExist($data)
{
$string = "SELECT student_number FROM users WHERE student_number = :user";
$sth = $this->db->prepare($string);
$sth->execute(array(
':user' => $data['user']
));
return $sth->rowCount() == 0 ? true : false;
}
public function validate($data) {
$this->userExist($data);
}
What i want is to return a string, that says "user exists", if the userExist method is false ... But this code doesn't work:
if($sth->rowCount() == 0) {
return true;
} else {
return "User Already Exists";
}
This is, how i call them in the controller:
if ($this->model->validate($data) == true) {
$this->model->create($data);
header('Location: '.URL.'users');
} else {
echo $this->model->validate($data);
die();
}
What do you think is the best solution?
First of all, you need to return the value of validate:
public function validate($data) {
$this->userExist($data);
}
But there are some other problems here. You don't need to call $this->model->validate($data) twice in your controller. You could do something like:
$result = false;
$result = $this->model->validate($data);
if ( true === $result {
$this->model->create($data);
header('Location: '.URL.'users');
} else {
die($result);
}
I have a general create function that submits a new user to the database - this works fine. Where I am is stuck is the following.
I know that I need the user that is signing up to have clicked the link in the email before the account can login. How do I implement that into my if statement when I run the create function?
I am a bit confused as to how to set my errors if any thing is correct or wrong to do with the activation process I have currently set the messages using $this->form_validation->set_message();. Do I need to use set_flashdata();? and how will echo these into the view?
When I create a new user I have the userActive field set at 0 by default and also the default group is set to users
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function index()
{
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['pageTitle'] = "Create User";
$this->load->view('frontend/assets/header', $data);
$this->load->view('frontend/users', $data);
$this->load->view('frontend/assets/footer');
}
public function create(){
//If form validation fails load previous page with errors else do the job and insert data into db
if($this->form_validation->run('createUser') == FALSE)
{
$data['success'] = "";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$passwordHash = $this->encrypt->sha1($password); // Lets encrypt the password why sha1? MD5 is for tossers
$activateCode = $this->_activateCode(10);
// If the data is correct follow through with db insert
if($this->users_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$activateCode))
{
$data['success'] = TRUE;
redirect('frontend/users/create','refresh');
}
}
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['pageTitle'] = "Create User";
$this->load->view('frontend/assets/header', $data);
$this->load->view('frontend/user_create', $data);
$this->load->view('admin/assets/footer');
echo get_class($this);
var_dump(method_exists($this, '_activateCode'));
}
function _userRegEmail($activateCode,$email,$firstname,$lastname){
$data['companyName'] = $this->core_model->companyDetails()->coreCompanyName;
$data['companyEmail'] = $this->core_model->companyDetails()->coreCompanyEmail;
$data['companyContact'] = $this->core_model->companyDetails()->coreContactName;
$data['firstName'] = $firstName;
$data['lastName'] = $lastname;
$data['email'] = $email;
$data['activateCode'] = $activateCode;
$this->email->from($this->core_model->companyDetails()->coreCompanyEmail, $this->core_model->companyDetails()->coreCompanyName);
$this->email->to($email);
$this->email->subject($this->core_model->companyDetails()->coreCompanyName, 'User Registration Confirmation');
$messageContent= $this->load->view('email_templates/userReg','', TRUE);
$this->email->message($messageContent);
//$this->email->send();
}
function usersconfirm(){
$activateCode = $this->uri->segment(3);
if($activateCode == '')
{
$this->form_validation->set_message('userConfirmError', 'Sorry you did not have a correct Activation Code.');
}
$userConfirmed = $this->users_model->confirm_user($activateCode);
if($userConfirmed){
$this->form_validation->set_message('userConfirmed', 'Thanks your account is now active you may login!');
}else{
$this->form_validation->set_message('userRecord', 'I am sorry we do not have any details with that Activation Code');
}
}
function _username_check($username)
{
if($this->users_model->username_taken($username))
{
$this->form_validation->set_message('username_check', 'Sorry the username %s is taken!');
return FALSE;
}else{
return TRUE;
}
}
function _email_check($email)
{
if($this->users_model->email_check($email))
{
$this->form_validation->set_message('email_check','Sorry there is already a user with this %s');
return FALSE;
}else{
return TRUE;
}
}
function _activateCode($length)
{
return random_string('alnum', $length);
}
}
/* End of file users.php */
/* Location: ./application/controllers/users.php */
You can determine if the user has clicked the activation link by checking the database for userActive in your if statement.
You can use flash data, sure. You can retrieve flash data with:
$this->session->flashdata('item'); to echo out to the view.
See http://codeigniter.com/user_guide/libraries/sessions.html > flash data