I have created a basic login form with validation containing only that the fields are not empty.
In controller the index looks like
$this->load->helper('form');
$this->load->view('auth/login');
and this is the view
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<meta charset="utf-8">
<title>LOGIN
</title>
</head>
<body>
<h1>Simple Login with CodeIgniter</h1>
<?php echo form_open('login/verifylogin'); ?>
<div class="" style="margin:0">
<label for="username">Username:</label>
<div class="" style="display:inline-block;margin:0">
<?php echo form_input(['name'=>'username','class'=>'','placeholder'=>'Your username here','value'=>set_value('username')]); ?>
</div>
<?php echo form_error('username',"<div class='w3-text-red' style='display:inline-block'>","</div>"); ?>
</div>
<br/>
<div class="">
<?php echo form_label('Password:','pass'); ?>
<div class="" style="display:inline-block;margin:0">
<?php echo form_password(['name'=>'password','class'=>'','placeholder'=>'Your password here']); ?>
</div>
<?php echo form_error('password',"<div class='w3-text-red' style='display:inline-block'>","</div>"); ?>
</div>
<br/>
<?php echo form_submit('submit', 'Login'); ?>
<?php echo form_close(); ?>
</form>
</body>
</html>
When a user is successfully validated he is redirected to dashboard view but in address bar still I get http://192.168.1.102/login/verifylogin (192.168.1.102 is the localhost or specifically its my device address on which server is running).
Also if a user leaves a field empty then he is showed the view auth/login with respective errors but the address bar shows http://192.168.1.102/login/verifylogin.
Please guide me how to fix this.
I am a beginner in codeigniter (I also have hands on laravel).
I have removed the index.php file according to the given guide.
I use ubuntu 14.04
EDIT 1:- I don't want to display the method name in address bar if a user fails login
EDIT 2:- Controller:-
<?php
/**
*
*/
class Login extends CI_Controller
{
public function index()
{
$this->load->helper('form');
$this->load->view('auth/login');
}
public function verifylogin()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run()) {
$this->load->helper('url');
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('Loginmodel');
if ($this->Loginmodel->login_valid($username, $password)) {
redirect('dashboard');
}else {
$this->load->view('auth/login');
}
} else {
$this->load->view('auth/login');
}
}
}
?>
Related
I am a beginner. I dont have any professional degree on coding. I have learnt through internet only. I have developed a few pages which will be connected to database. I have tried to login using username and password and it successfully redirects to the home page. Now I want the username to be displayed on the home page after login. please help. what modifications do I need to do ??
login_save.php code is as below-
<?php
function SignIn($loginname,$pass) {
//require_once '../../common/createdbconn.php';
$login_id='';
$login_status='';
$error_message= '';
if(!empty($loginname) && !empty($pass)){ //checking the 'user' name and password, is it empty or have some text
$login_id=validate_login($loginname,$pass);
if ($login_id != '') {
$login_status=$login_id;
}
else {
//empty check
$error_message=NO_USERNAME;
$login_status=$error_message;
}
return $login_status;
}
}
function validate_login($loginname,$pass) {
require '../../common/createdbconn.php';
// validate user
$sql="SELECT id, fullname from m_user where login_name='$loginname' and password='$pass'";
//$sql="SELECT mu.id as id, mu.fullname as fullname, mu.office_id as office_id, xurm.role_id as role_id from m_user mu, x_user_role_mapping xurm where mu.id = xurm.user_id and mu.login_name='$loginname' and mu.password='$pass'";
$result=mysqli_query($conn,$sql);
$login_id=mysqli_fetch_row($result);
session_start();
$sessionid = session_id();
$sql_sessionid="update m_user set session_id='$sessionid' where login_name='$loginname'";
$result=mysqli_query($conn,$sql_sessionid);
$_SESSION['login_id']=$login_id[0];
$_SESSION['fullname']=$login_id[1];
$_SESSION['logged_in']=true;
$_SESSION['loginname']=$loginname;
return $login_id[0];
}
?>
login_action.php code
<?php
require_once '../../common/createdbconn.php';
require_once '../model/login_save.php';
$loginname=$_POST["user"];
$password=$_POST["pass"];
$pass=md5($password);
$login_status='';
$login_status=SignIn($loginname,$pass);
if ($login_status=='' || $login_status=='NO_USERNAME') { // Validation passed
session_start(); //starting the session for user profile page
$error ="Username or Password is invalid";
header("location:../view/login.php?session_id=".session_id());
}
else{
header("location:../../cbs/view/home.php?login_status=$login_status");
session_destroy();
}
?>
login.php code
<!DOCTYPE html>
<?php
require '../../common/createdbconn.php';
?>
<html>
<head>
<meta charset="UTF-8">
<title>CBS HELPDESK,ASSAM CIRCLE</title>
<link rel="icon" href="../../images/IP.png" type="image/png" sizes="100x56">
<link rel="stylesheet" href="../../css/style.css">
</head>
<body>
<img src="../../images/indiapost.jpg" style="width:1600px;height:120px;">
<h1>Welcome to Circle Processing Centre-Assam</h1>
<div style="color: Red;">
<p>
<?php
echo (isset($_GET['login_status']) ? htmlentities($_GET['login_status'], ENT_QUOTES) : '');
?>
</p>
</div>
<div class="wrapper">
<div class="container">
<h2>Login to Continue</h2>
<form method="post" action="../controller/login_action.php" class="form">
<input id="user" name="user" type="text" placeholder="Enter Your UserID">
<input id="pass" name="pass" type="password" placeholder="Enter Your Password">
<button id="login" name="login" type="submit">LogIn</button>
</form>
</div>
</div>
</body>
</html>
home.php
<!DOCTYPE html>
<html>
<head>
<title>CBS HELPDESK,ASSAM CIRLCE</title>
<link rel="stylesheet" href="../../css/home_style.css">
<link rel="icon" href="../../images/IP.png" type="image/png" sizes="100x56">
<script type="text/javascript">
var tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
function GetClock(){
var d=new Date();
var nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds();
if(nmin<=9) nmin="0"+nmin
if(nsec<=9) nsec="0"+nsec;
document.getElementById('clockbox').innerHTML=""+tmonth[nmonth]+" "+ndate+", "+nyear+" "+nhour+":"+nmin+":"+nsec+"";
}
window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>
</head>
<body>
<h1>Circle Processing Centre(CBS)<br>
O/O The Chief Postmaster General, Assam-781001</h1>
<header>
<marquee style="font-size:50px;" behavior="scroll" direction="left">CBS Offices as on <?php echo date("d-m-y");?> = 507</marquee>
</header>
<nav>
<ul>
<li>User Related Requests</li>
<li>List of CBS Offices in Assam</li>
<li>Migration Plans</li>
<li>ATM Sites-Assam</li>
<li>FAQs/Instrcutions/Orders</li>
<li>Contact Us</li>
<li>Logout</li></ul>
</nav>
<section>
<table>
<tr>
<th>Division</th>
<th>No of Total Offices</th>
<th>No of CBS Offices</th>
<th>Achievement in %</th>
</tr>
</table>
</section>
<footer>
<div id="clockbox">
</div>
</footer>
</body>
</html>
In home.php, you should first check if the session exists and redirect to the login page (if it's not already done).
Then you could display the ursername like this anywhere you want :
<div><?php echo $_SESSION['fullname']; ?></div>
or
<div><?= $_SESSION['fullname'] ?></div>
Hope you are saving logged in user name in $_SESSION['loginname']=$loginname;
Use session_start(); at the starting of login_save.php and <?php session_start(); ?> at the starting of home.php
User name you can call in home.php using
$name=$_SESSION['loginname'];
echo $name;
I think you are using login_name as username in your table.
You store login_name in session so simply display the username from session.
Don't forget start session on home page and always start session on the top of page.You start session in the middle of code on login_save.php
Use this code on your home page
<?php
session_start();
echo $_SESSION['login_name'];
?>
i' newbie code iginiter 3 with mysql database, and xampp v3.2 .
Error 'The address wasn't understood' when i click login button.
help me ...
this config
<code>`enter code here`
$config['base_url'] = 'localhost:8087/hris/';
$config['index_page'] = 'login.php';
</code>
and my route.php
<code>
$route['default_controller'] = 'user_authentication';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>
how to fix this error....
user_authentication.php
Class User_Authentication extends CI_Controller
{
//session_start(); //we need to start session in order to access it through CI
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('login_database');
}
// Show login page
public function index()
{
$this->load->view('login');
}
// Show registration page
public function user_registration_show()
{
$this->load->view('registration_form');
}
// Validate and store registration data in database
public function new_user_registration()
{
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username','trim|required|xss_clean');
$this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('registration_form');
} else
{
$data = array(
'user_name' => $this->input->post('UserID'),
'user_email' => $this->input->post('email_value'),
'user_password' => $this->input->post('password')
);
$result = $this->login_database->registration_insert($data);
if ($result == TRUE)
{
$data['message_display'] = 'Registration Successfully !';
$this->load->view('login_form', $data);
} else {
$data['message_display'] = 'Username already exist!';
$this->load->view('registration_form', $data);
}
}
}
// Check for user login process
public function user_login_process()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin_page');
}else{
$this->load->view('login_form');
}
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE)
{
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false)
{
$session_data = array(
'username' => $result[0]->user_name,
'email' => $result[0]->user_email,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('admin_page');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}
// Logout from admin page
public function logout()
{
// Removing session data
$sess_array = array(
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('login_form', $data);
}
}
?>
this models login_database.php
Class Login_Database extends CI_Model
{
// Insert registration data in database
public function registration_insert($data)
{
// Query to check whether username already exist or not
$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0)
{
// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0)
{
return true;
}
} else {
return false;
}
}
// Read data using username and password
public function login($data)
{
$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($username) {
$condition = "user_name =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
this view ( login.php )
$this->load->helper('form');
if (isset($this->session->userdata['logged_in'])) {
header("location: http://localhost/login/index.php/user_authentication/user_login_process");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Global stylesheets -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
<link href="assets/css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
<link href="assets/css/minified/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/minified/core.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/minified/components.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/minified/colors.min.css" rel="stylesheet" type="text/css">
<!-- /global stylesheets -->
<!-- Core JS files -->
<script type="text/javascript" src="assets/js/plugins/loaders/pace.min.js"></script>
<script type="text/javascript" src="assets/js/core/libraries/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/core/libraries/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/plugins/loaders/blockui.min.js"></script>
<!-- /core JS files -->
<!-- Theme JS files -->
<script type="text/javascript" src="assets/js/plugins/forms/styling/uniform.min.js"></script>
<script type="text/javascript" src="assets/js/core/app.js"></script>
<script type="text/javascript" src="assets/js/pages/login.js"></script>
<!-- /theme JS files -->
</head>
<body>
<!-- Main navbar -->
<div class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="index.html"><img src="assets/images/logo_light.png" alt=""></a>
<ul class="nav navbar-nav pull-right visible-xs-block">
<li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
</ul>
</div>
</div>
<!-- /main navbar -->
<!-- Page container -->
<div class="page-container login-container">
<!-- Page content -->
<div class="page-content">
<!-- Main content -->
<div class="content-wrapper">
<!-- Content area -->
<div class="content">
<?php
echo form_open('user_authentication/user_login_process');
?>
<!-- Advanced login -->
<form action="" method="post">
<div class="panel panel-body login-form">
<div class="text-center">
<div class="icon-object border-slate-300 text-slate-300"><i class="icon-reading"></i></div>
<h5 class="content-group">Login to your account <small class="display-block">Your credentials</small></h5>
</div>
<div class="form-group has-feedback has-feedback-left">
<input type="text" class="form-control" placeholder="Username" name="userid" id="userid" required>
<div class="form-control-feedback">
<i class="icon-user text-muted"></i>
</div>
</div>
<div class="form-group has-feedback has-feedback-left">
<input type="text" class="form-control" placeholder="Password" name="pass" id="pass" required>
<div class="form-control-feedback">
<i class="icon-lock2 text-muted"></i>
</div>
</div>
<div class="form-group login-options">
<div class="row">
<div class="col-sm-6">
<label class="checkbox-inline">
<input type="checkbox" class="styled" checked="checked">
Remember
</label>
</div>
<div class="col-sm-6 text-right">
Forgot password?
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn bg-blue btn-block">Login <i class="icon-arrow-right14 position-right"></i></button>
</div>
<?php echo form_close(); ?>
<div class="content-divider text-muted form-group"><span>Don't have an account?</span></div>
Sign up
</div>
</form>
<!-- /advanced login -->
</div>
<!-- /content area -->
</div>
<!-- /main content -->
</div>
<!-- /page content -->
</div>
<!-- /page container -->
</body>
</html>
</pre></code>
try to change your form open in to this
<?php
echo form_open(base_url('User_Authentication/user_login_process'));
?>
For anyone who face the problem of The address wasn't understood when clicking a link for example, just make sure to add http:// to the $config['base_url'] value, in the case of the question above, you should replace :
$config['base_url'] = 'localhost:8087/hris/';
by
$config['base_url'] = 'http://localhost:8087/hris/';
Hope this help :)
I just upload my website from localhost to hostinger with filezilla.
I already configure the database setting and all working well, but i get different result if i want login to the website. it give error "the username or password is wrong".
After that, I run the website in my localhost. Login with same username/ password and its working.
I dont know the error, i use same code between the local and hostinger
controller/login.php
<?php
class Login extends CI_Controller {
function __construct() {
parent::__construct();
session_start();
$this->load->model(array('mlogin'));
if ($this->session->userdata('email')) {
$this->load->view('header1');
}
elseif (!$this->session->userdata('email')) {
$this->load->view('header');
}
}
function index() {
$this->load->view('login');
}
function proses() {
$this->form_validation->set_rules('email', 'email', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
$usr = $this->input->post('email');
$psw = $this->input->post('password');
$u = mysql_real_escape_string($usr);
$p = md5(mysql_real_escape_string($psw));
$cek = $this->mlogin->cek($u, $p);
if ($cek->num_rows() > 0) {
//login berhasil, buat session
foreach ($cek->result() as $qad) {
$sess_data['u_id'] = $qad->u_id;
$sess_data['nama'] = $qad->nama;
$sess_data['email'] = $qad->email;
$sess_data['role'] = $qad->role;
$this->session->set_userdata($sess_data);
}
redirect('home');
} else {
$this->session->set_flashdata('result_login', '<br>Username atau Password yang anda masukkan salah.');
redirect('login');
}
}
}
function logout() {
$this->session->sess_destroy();
redirect('login');
}}
model/mlogin.php
<?php
class Mlogin extends CI_Model {
private $table = "user";
function cek($email, $password) {
$this->db->where("email", $email);
$this->db->where("u_paswd", $password);
return $this->db->get("user");
}
function semua() {
return $this->db->get("user");
}
function cekKode($kode) {
$this->db->where("email", $kode);
return $this->db->get("user");
}
function cekId($kode) {
$this->db->where("u_id", $kode);
return $this->db->get("user");
}
function getLoginData($usr, $psw) {
$u = mysql_real_escape_string($usr);
$p = md5(mysql_real_escape_string($psw));
$q_cek_login = $this->db->get_where('users', array('email' => $u, 'password' => $p));
if (count($q_cek_login->result()) > 0) {
foreach ($q_cek_login->result() as $qck) {
foreach ($q_cek_login->result() as $qad) {
$sess_data['logged_in'] = 'vera';
$sess_data['u_id'] = $qad->u_id;
$sess_data['email'] = $qad->email;
$sess_data['nama'] = $qad->nama;
$sess_data['group'] = $qad->group;
$sess_data['rid'] = $qad->rid;
$this->session->set_userdata($sess_data);
}
redirect('main');
}
} else {
$this->session->set_flashdata('result_login', '<br>Username atau Password yang anda masukkan salah.');
header('location:' . base_url() . 'login');
}
}
function update($id, $info) {
$this->db->where("u_id", $id);
$this->db->update("user", $info);
}
function simpan($info) {
$this->db->insert("user", $info);
}
function hapus($kode) {
$this->db->where("u_id", $kode);
$this->db->delete("user");
}
}
view/login.php
<html>
<head>
<meta charset="UTF-8">
<title>Log in</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<!-- Font Awesome Icons -->
<link href="<?php echo base_url('assets/css/font-awesome.min.css'); ?>" rel="stylesheet">
<!-- Theme style -->
<link href="<?php echo base_url('assets/css/AdminLTE.min.css'); ?>" rel="stylesheet">
<!-- iCheck -->
<link href="<?php echo base_url('assets/js/plugins/iCheck/square/blue.css'); ?>" rel="stylesheet">
</head>
<body>
<body class="login-page">
<div class="login-box">
<div class="login-logo">
<div class="login-box-body">
<h2>Login</h2>
<form action="<?php echo site_url('login/proses'); ?>" method="post">
<?php
if (validation_errors() || $this->session->flashdata('result_login')) {
?>
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Warning!</strong>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('result_login'); ?>
</div>
<?php } ?>
<div class="form-group has-feedback">
<input type="email" name="email" class="form-control" placeholder="Username"/>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password"/>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div>
<button type="submit" class="btn btn-primary btn-block btn-flat">Masuk</button>
<br>
<h4>Daftar Anggota Baru</h4>
</div><!-- /.col -->
</div>
</form>
</div><!-- /.login-box-body -->
</div><!-- /.login-box -->
<!-- jQuery 2.1.3 -->
<script src="<?php echo base_url('assets/js/plugins/jQuery/jQuery-2.1.3.min.js'); ?>"></script>
<!-- Bootstrap 3.3.2 JS -->
<script src="<?php echo base_url('assets/js/bootstrap.min.js'); ?>"></script>
<!-- iCheck -->
<script src="<?php echo base_url('assets/js/plugins/iCheck/icheck.min.js'); ?>"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script>
$(function () {
$("#slider").responsiveSlides({
auto: true,
nav: true,
speed: 500,
namespace: "callbacks",
pager: true,
});
});
</script>
<!--footer-starts-->
<?php $this->load->view('footer') ?>
<!---->
</div>
</body>
</html>
localhost php version 5.6.11
hostinger php version 5.6.18
Hostinger sensitive with capitalization
change this code
$this->form_validation->set_rules('email', 'email', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
with this
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean');
and i think this code will give you 0 for $p
$p = md5(mysql_real_escape_string($psw));
just use this
$p = md5($psw);
I am a newbee to CodeIgniter and PHP. I am trying to insert data using a form and display it on the same view page using MVC pattern given by CodeIgniter. My View is:
<html>
<head>
<title>My Form</title>
</head>
<body>
<? echo form_open('books/input'); ?>
<? echo $id; ?>:
<? echo form_input('id'); ?>
</br>
<? echo $title; ?>:
<? echo form_input('title'); ?>
</br>
<? echo $body; ?>:
<? echo form_input('body'); ?>
</br>
<? echo form_submit('mysubmit','Submit!'); ?>
<? echo form_close(); ?>
</body>
</html>
and My Controller is:
<? class Books extends Controller{
function Books(){
parent::Controller();
}
function main(){
$this->load->model('books_model');
$data = $this->books_model->general();
//$this->load->view('books_main',$data);
}
function input(){
$this->load->helper('form');
$this->load->model('books_model');
$data = $this->books_model->general();
$this->load->view('books_input',$data);
}
} ?>
and My model is just returning the data entered by the user as:
<? class books_model extends Model{
function books_model(){
$this->load->helper('url');
}
function general(){
$data['id'] = 'id';
$data['title'] = 'title';
$data['body'] = 'body';
return $data;
}
} ?>
But when I try to access the form, it shows me an error quoting:
load->model('books_model'); $data = $this->books_model->general(); }
function input(){ $this->load->helper('form'); $this->load->model('books_model'); $data = $this->books_model->general();
$this->load->view('books_input',$data); } } ?>
404 Page Not Found
though I am accessing it with the same URL: localhost/CodeIgniter/index.php/books/input
How can I access this form and insert data successfully?
Every Class name should start with capital letter
like
class Books_model extends Model
and do type like this
$this->load->model('Books_model');
this could be the issue that you are getting "404 page not found".
Read some basic things that you have to follow from guide
http://ellislab.com/codeigniter/user-guide/general/models.html
in your framework are there any automation to build forms?
For example let's say you have this array of fields:
$fields = array('name'=>array('type'=>'input',otherparams)
'desc'=>array('type'=>'textarea',otherparams)
);
based on fields you should make HTML like this:
<form>
Name: <input name="name" type="text">
Description: <textarea name="desc"></textarea>
//>Submit
</form>
Do you build your html by-hand or is there some sort of automation?
Thanks
I work with the Yii framework. The php generates the html automatically. You write some html by hand but it's for the views. The views also have dynamic php variables that change. The actually full html document is put together by calling a controller with the web address, that controller deciding what models if any it needs to apply to the form and what view to put the model in. Then it generates the html.
SiteController.php
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
ContactForm.php = This is the model.
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
This is the view:
contact.php
<?php
$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
'Contact',
);
?>
<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Going to the page: http://yoursite/index.php/contact/ activates the actionContact method in the SiteController. That grabs the posted contact information, puts it into a model, and then renders a view.
CodeIgniter allows you to build forms using the Form Helper, although I prefer to write the HTML myself.
try this(not tested)
<?php
$fields = array('name'=>array('type'=>'input',name='fname')
'desciprtion'=>array('type'=>'textarea',name='desc')
);
?>
<form name="myform" action="" method="post">
<?php
foreach($fields as $key=>$value)
{
echo "<label>$key</label>";
echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\">
}
?>