I have made the redirect from the question i have posted here
Now i have another form in the redirected page where i need to enter name and mobile number and if it matches in my db table helloworld it will go to one page or else to another
<p>You have successfully registered</p>
<div>
<label>Login</label>
</div>
<div>
<form action="" method="post">
<label> Username </label>
<strong>:</strong>
<input class="input-text required-entry" type="text" name="fname" maxlength="20">
<label>Mobile No</label>
<strong>:</strong>
<input class="required-entry" type="number" maxlength="10" name="mobileno">
<input type="submit" name="login" value="Login">
<input type="button" name="cancel" value="Cancel">
</form>
</div>
Can any one help me how no i can verify it with existing data in db and make this work ? Shall I start it with using index controller or is there any magento way?
Update:
this is my Indexcontroler.php after below answer update
<?php
class MyCustom_Helloworld_IndexController extends Mage_Core_Controller_Front_Action
{
/*
* this method privides default action.
*/
public function indexAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
echo $firstname = $param['fname'];
$lastname = $param['lname'];
$address = $param['address'];
$state = $param['state'];
$city = $param['city'];
$mobile = $param['mobileno'];
$model = Mage::getModel('helloworld/helloworld');
// $model->setTitle($title);
$model->setFirstname($firstname);
$model->setLastname($lastname);
$model->setAddress($address);
$model->setState($state);
$model->setCity($city);
$model->setMobileno($mobile);
$model->save();
$this->_redirect('helloworld/index/login');
// $this->_redirectReferer();
}else {
/*
* Initialization of Mage_Core_Model_Layout model
*/
$this->loadLayout();
/*
* Building page according to layout confuration
*/
$this->renderLayout();
}
}
public function loginAction()
{
$this->loadLayout();
$this->renderLayout();
}
public function loginnAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
$username = $param['fname'];
$mobile = $param['mobileno'];
$check = Mage::getModel('helloworld/helloworld')
->AddFieldToFilter('mobileno', array('eq' => $mobile))
->AddFieldToFilter('fname', array('eq' => $username));
if(count($check)==1) {
$this->_redirectReferer();
}else {
$this->_redirect('helloworld/index/login');
}
}
}
}
you can add check like that
public function loginAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
$username = $param['fname'];
$mobile = $param['mobile'];
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
$table = $connectionresource->getTableName('helloworld/helloworld');
$allrecord = $readconnection->select()->from(array('helloworld'=>$table))->where('helloworld.mobileno=?', $mobileno)
->where('helloworld.fname=?', $username);
$alldata =$readconnection->fetchAll($allrecord);
if(count($alldata)==1) {
$this->_redirect('home');
}else {
$this->_redirect('customer/account');
}
}
Related
Guys Im new to php and codeigniitor. Im trying to make a post application but it's not working please help.
here is my controller function
public function status(){
$this->load->library('form_validation');
$this->form_validation->set_rules('post', 'Post Something', 'required');
if ($this->form_validation->run() == FALSE) {
$user = $this->session->userdata('user');
$data1['user'] = $user;
$this->load->view('pages/panel',$data1);
}
else{
$this->load->model('reg_model');
$formArray1 = array();
$formArray1['post'] = $this->input->post('post');
$formArray1['posted_by'] = $user['ID'];
$this->reg_model->create1($formArray);
$this->session->set_flashdata('msg', 'Your account is created successfully');
redirect(base_url().'index.php/Registration/panel');
}
here is my form
<?php echo validation_errors();?>
<form action = " <?php echo base_url()?>registration/status" name= "registrationForm1" id="registrationForm1" method = "post">
<label class =" form-control" for="post">Post Something</label></br>
<textarea style =" width:100%" class="form-control" rows="3" id="post" placeholder="Your message..."></textarea>
<p class ="invalid-feedback"><?php echo form_error('posts');?></p></br>
<button type="submit" class="btn btn-primary btn-block">Post</button>
</form>
my model:
public function create1($formArray1)
{
$this->db->insert('posts', $formArray1);
}
You should use $formArray1 not $formArray
$formArray1 = array();
$formArray1['post'] = $this->input->post('post');
$formArray1['posted_by'] = $user['ID'];
$this->reg_model->create1($formArray1);
and in Model:-
public function create1($formArray1)
{
$this->db->insert('users', $formArray1);
}
Hi everyone,
Im trying to figure out why my script keeps redirecting to my login page. So far I haven't found it yet. Could someone explane to me which mistakes I'm making?
This is my code.
functions.php
function redirect_to($location = NULL) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
function include_layout_template($template="") {
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
index.php
<?php
require_once('../../includes/initialize.php'); ?>
<?php if (!$session->is_logged_in()) { redirect_to("login.php"); } ?>
<?php include_layout_template("admin_header.php"); ?>
Logout
<?php include_layout_template("admin_footer.php"); ?>
session.php
<?php
class Session {
public $logged_in = false;
public $user_id;
public $message;
function __construct() {
session_start();
$this->check_message();
$this->check_login();
if($this->logged_in) {
// actions to take right away if user is logged in
} else {
// actions to take right away if user is not logged in
}
}
public function login_user($user) {
if($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
private function check_message() {
// Is there a message stored in the session?
if(isset($_SESSION['message'])) {
// Add it as an attribute and erase the stored version
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
//$message = $session->message();
user.php
<?php
require_once('../../includes/initialize.php');
class Users extends DatabaseQuery
{
protected $tablename = 'users';
protected $db_fields = array('id', 'first_name', 'last_name', 'password', 'username');
public $id;
public $first_name;
public $last_name;
public $password;
public $username;
public static function create_user($first_name, $last_name, $password, $username)
{
global $database;
$sql = "INSERT INTO users (";
$sql .= "first_name, last_name, password, username) ";
$sql .= "VALUES (";
$sql .= "'{$first_name}', '{$last_name}', '{$password}', '{$username}')";
$result = $database->query($sql);
return $result;
}
public static function find_username($username) {
global $database;
$sql = "SELECT * FROM users ";
$sql .= "WHERE username= '{$username}' ";
$sql .= "LIMIT 1";
$result = $database->query($sql);
$admin = mysqli_fetch_assoc($result);
return $admin;
}
public static function find_password($username, $password) {
global $database;
$sql = "SELECT * FROM users ";
$sql .= "WHERE username= '{$username}' ";
$sql .= "And password=".crypt($password) ;
$sql .= " LIMIT 1";
$result = $database->query($sql);
$admin = mysqli_fetch_assoc($result);
return $admin;
}
public static function password_check($password, $existing_hash) {
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
public static function login($username, $password) {
$admin = self::find_username($username);
if ($admin) {
// found username, check password.
if (self::password_check($password, $admin['password'])) {
//password matches
return $admin;
} else {
//password does not match
return false;
}
} else {
// admin not found
return false;
}
}
}
$user = new Users();
login.php
<?php
/**
* FIRSTNAME LASTNAME PASSWORD USERNAME
* Coos Wolff secret Admin
* Kevin Doofus password Kevin
*/
include_once("../../includes/initialize.php");
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$login = Users::login($username, $password);
if($login) {
$session->logged_in = true;
redirect_to('index.php');
} else {
redirect_to('login.php');
}
} ?>
<form id='login' action='create_user.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Create User</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName:</label>
<input type='text' name='username' id='username' maxlength="50" />
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" />
<label for='firstName' >FirstName:</label>
<input type='text' name='first_name' id='first_name' maxlength="50" />
<label for='lastName' >LastName:</label>
<input type='text' name='last_name' id='last_name' maxlength="50" />
<input type='submit' name='submit' value='Submit' />
</fieldset>
</form>
<hr /><br /><hr />
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName:</label>
<input type='text' name='username' id='username' maxlength="50" VALUE="Kevin"/>
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" />
<label for='firstName' >FirstName:</label>
<input type='text' name='first_name' id='first_name' maxlength="50" value="Kevin" />
<label for='lastName' >LastName:</label>
<input type='text' name='last_name' id='last_name' maxlength="50" value="Doofus"/>
<input type='submit' name='submit' value='Submit' />
</fieldset>
</form>
If I submit the form without the code to check if somebody is logged in the code works fine. But with the checking code it keeps redirecting me to the login page. After submitting the form I set $session->logged_in = true. But still nothing. I have look on google to see what im doing wrong. But I can't figure it out. I tried many different codes but it all ends up the same way. Redirecting me to the login in page. It's probably an easy fix. But I just can't see it. Could somebody tell me what I am doing wrong?
Kind Regards,
Coos
You are going to laugh when I tell you this. According to the documentation:
If the return is omitted the value NULL will be returned.
public function is_logged_in() {
// Add the return statement
return $this->logged_in;
}
It is returning NULL, which is a "falsy" value so your check thinks it's not logged in.
I have been practicing with PHP and mongodb. I am developing a simple web application but using OOP.
I created a class called user which has my methods to do with user like addUser, deleteUser etc. For add user, I would like for the form to carry out some simple validation tasks, but i am not sure how. Here is the class to add a new user:
function createUser($username, $name, $email, $password){
$user = array(
'username' => $username,
'name' => $name,
'email' => $email,
'password' => $password
);
if ($this->db->count(array('username' => $username)) == 0) {
$this->db->insert($user);
return true;
} else {
echo 'username taken';
}
}
And the html:
<?php
session_start();
include_once 'user.php';
include './templates/header.php';
if (isset($_POST['register']) && ($_POST['register']) == ($_POST["register"])) {
$user = new User();
$return = $user->createUser(
$_POST['username'],
$_POST['name'],
$_POST['email'],
$_POST['password'],
$_POST['password2']);
}
if ($return == true) {
echo 'you have successfully registered';
} else {
echo '</br>' . 'sorry, try again';
}
?>
<div class="container">
<div class="jumbotron">
<form method="post" action="">
<label>Username: </label><br>
<input name="username" type="text" ><br><br>
<label>Name: </label><br>
<input name="name" type="text"><br><br>
<label>Email: </label><br>
<input name="email" type="email" ><br><br>
<label>Password: </label><br>
<input name="password" type="password" ><br><br><br>
<label>Repeat Password: </label><br>
<input name="password2" type="password" ><br><br><br>
<input name="register" class="btn btn-primary btn-lg" type="submit" value="Register"><br>
</form>
</div>
</div>
Please feel free to correct me on other mistakes you may notice. I know there is bound to be some.
i wrote a simple example for you its simple and useful
class validation {
public $currentValue;
public $values = array();
public $errors = array();
public function __construct() {
parent::__construct();
// echo "burasi model sayfasi ";
}
public function post($key){
if(isset($_POST[$key])){
$this->values[$key] = $_POST[$key];
$this->currentValue = $key;
return $this;
}else{ die("hi boo boo ! your form values are empty");}
}
public function isEmpty(){
if(empty($this->values[$this->currentValue])){
$message='the form is emppty';
$this->errors[$this->currentValue]['empty'] =''.$message.'';
}
return $this;
}
public function submit(){
if(empty($this->errors)){
return true;
}else{
return false;
}
}
}
this is an example so how can you use it ?
firstly you need yo call the class
$form = new validation ();
$form->post("all you need just write post name here ")
->isEmpty();
if($form->submit()){
//everyting is ok !
you cann add delet or update data
}else{
$data["error"] = $form->errors; // and we sett the errorr mesages to the array now you can show the user the errormesages ! well done
}
}
I'm having trouble updating the data in the database with codeigniter. This is my controller :
public function update_mission_vision($id)
{
$this->securePage();
$data['mission'] = $mission = $this->about_model->get_mission_vision($id);
if ($mission == false) {
$this->session->set_flashdata('msg', 'The mission does not exist.');
redirect('about/manage-miteri-mission-vision');
} else {
if ($this->input->post('submit')) {
$this->form_validation->set_rules('title', 'title', 'required|max_length[240]');
$this->form_validation->set_rules('details', 'details', 'required|max_length[240]');
if ($this->form_validation->run()) {
$added_on = time();
$this->about_model->update_mission_vision($added_on, $id);
$this->session->set_flashdata('msg', 'mission updated successfully.');
redirect('about/manage-miteri-mission-vision');
}
}
}
$data['title'] = "$mission->title | miteripkr.com";
$data['keywords'] = "$mission->title";
$data['content'] = $this->load->view('about-us/update_mission_vision', $data, true);
$this->load->view('miteri', $data);
}
And this is my models :
function get_all_mission_vision($limit = null, $offset = null)
{
if ($limit)
{
$this->db->limit($limit. $offset);
}
return $this->db->get('mission_vision');
}
function get_mission_vision($id)
{
$this->db->where('id', $id);
$query = $this->db->get('mission_vision');
if ($query->num_rows()) {
return $query->row();
} else {
return false;
}
}
function update_mission_vision($id, $added_on)
{
$this->db->where('id', $id);
$this->db->set('title', $this->input->post('title'));
$this->db->set('details', $this->input->post('details'));
$this->db->set('added_on', $added_on);
$this->db->update('mission_vision');
}
This is my view :
<**div class="container-fluid" style="background:#fff; margin-top:10px; border-radius:5px; min-height:600px; margin-bottom:10px;">
<form action="" method="post" style="margin-top:30px;">
<?php echo $this->session->flashdata('msg');?>
<ol class="breadcrumb">
<li>admin</li>
<li>about us</li>
<li class="active">update mission & vision</li>
</ol>
<div class="form-group">
<label for="title"> Title for Post</label>
<input class="form-control" type="text" name="title" placeholder="Enter Title" value="<?php echo set_value('title', $mission->title)?>">
<?php echo form_error('title');?>
</div>
<div class="form-group">
<label for="title"> Details for Post</label>
<textarea class="ckeditor" name="details" placeholder="Enter Details" style="height:200px;"><?php echo set_value('details', $mission->details); ?></textarea>
<?php echo form_error('details');?>
</div>
<button class="btn btn-success" name="submit" type="submit" value="update"><span class="glyphicon glyphicon-ok"> update</span></button>
</form>
</div>
It even prints a success message but my data is not updated, why?
Maybe it's the call of the function update_mission_vision. You switched $id and $added_on.
And of course, like #Kamran Adil said, you have to give the post data to your model.
Update:
Here is an example how i write my update function in a model. So you can have look and make your own update function.
/**
* #name string TABLE_NAME Holds the name of the table in use by this model
*/
const TABLE_NAME = 'table';
/**
* #name string PRI_INDEX Holds the name of the tables' primary index used in this model
*/
const PRI_INDEX = 'field';
/**
* Updates selected record in the database
*
* #param Array $data Associative array field_name=>value to be updated
* #param Array $where Optional. Associative array field_name=>value, for where condition. If specified, $id is not used
* #return int Number of affected rows by the update query
*/
public function update(Array $data, $where = array()) {
if (!is_array($where)) {
$where = array(self::PRI_INDEX => $where);
}
$this->db->update(self::TABLE_NAME, $data, $where);
return $this->db->affected_rows();
}
Maybe you lost the $id in your URL.
Put a hidden input in your view with the $id, then in the controller, asign this $id = $this->input->post('id'); to get the $id. And the delete $id in your controller update_mission_vision() {
If I uncomment the below line then I am unable to get the value in $this->_request->getPost('Login')
//$this->setDecorators(array(array('viewScript', array('viewScript' => 'admin/login_decorator.phtml'))));
$this->_request->getPost works fine with forms but not with form decorator.
Below are the files...
forms/loinForm.php
<?php
class Application_Form_LoginForm extends Zend_Form {
public function __construct($options = null) {
parent::__construct($options);
$this->setMethod('post');
$name = new Zend_Form_Element_Text('username');
$name->removeDecorator('Label')
->removeDecorator("HtmlTag")
->addErrorMessage("Please Enter username")
->setRequired(true);
$password = new Zend_Form_Element_Password('password');
$password->removeDecorator('Label')
->removeDecorator("HtmlTag")
->addErrorMessage("Please Enter password")
->setRequired(true);
$submit = new Zend_Form_Element_Submit('Login');
$submit->removeDecorator('Label')
->removeDecorator("HtmlTag");
$this->addElements(array($name, $password, $submit));
//$this->setDecorators(array(array('viewScript', array('viewScript' => 'admin/login_decorator.phtml'))));
}
}
views/scripts/admin/login_decorator.phtml
<link href="<?php echo $this->baseUrl(); ?>/css/login.css" media="screen" rel="stylesheet" type="text/css">
<section class="container">
<div class="login">
<h1>Login to Administrator</h1>
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<p><input type="text" name="username" value="" placeholder="Username"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
<div class="login-help">
<p>Forgot your password? Click here to reset it.</p>
</div>
</section>
login.phtml
<?php echo $this->form; ?>
adminController.php loginAction()
public function loginAction() {
$mysession = new Zend_Session_Namespace('Admin');
if (isset($mysession->adminName)) {
$this->_redirect('/admin');
}
$form = new Application_Form_loginForm();
$this->view->form = $form;
//Preform Admin login action
if ($this->_request->getPost('Login')) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) { //If form data is valid
$name = $this->_request->getPost('username');
$password = $this->_request->getPost('password');
/* * **Creating object of model adminlogin class**** */
$adminLoginObj = new Application_Model_Adminlogin();
$fetchResult = $adminLoginObj->checkAdminAuthority($name, $password);
if (count($fetchResult) > 0) {
$mysession->adminName = $name;
$this->_redirect('/admin/');
} else {
$mysession->failLogin = "Invalid Username or Password!";
$this->_redirect('/admin/login');
}
}
}
}
I am unable to find out the reason for this issue.
Please help me to resolve this. Thanks in advance.
Please check
in your controller
if ($this->_request->getPost('Login')) { ...}
And in views/scripts/admin/login_decorator.phtml
<input type="submit" name="commit" value="Login">
name of the field is not matching with the action.
Please check it accordingly. I hope this will help you.