I have made a site in CodeIgniter2, but I can't get the forms to work, as I can't seem to even work out how to get it to post! Any help? Here is my code and the forms are only on the recommend, contact-us and support pages:
Form:
<div id="mainWhiteBox">
<h3>Tell people about us...</h3>
<p>If you know of a company or individual who need a really great design agency to help them with a project, let them know about us and benefit too. <br /><br />
<span class="customColour">We will give you £50 of Marks & Spencer vouchers for every client you recommend to us who goes on to become a client of xxxxx, it's that simple & there is no limit to the amount of vouchers you can earn!</span></p>
<div id="recommendSomeone">
<?php echo validation_errors(); print_r($_POST);?>
<?php echo form_open('recommend', array('id' => 'recommendForm')); ?>
<label for="friendName">Your Friend's Name</label>
<input type="text" id="friendName" value="<?php echo set_value('friendName'); ?>" />
<label for="friendEmail">Your Friend's Email Address</label>
<input type="email" id="friendEmail" value="<?php echo set_value('friendEmail'); ?>" placeholder="someone#youknow.com" />
<label for="customerName">Your Name</label>
<input type="text" id="customerName" value="<?php echo set_value('customerName'); ?>" />
<label for="customerEmail">Your Email Address</label>
<input type="email" id="customerEmail" value="<?php echo set_value('customerEmail'); ?>" placeholder="you#youremailaddress.com" />
<label for="friendConfirm"><input type="checkbox" id="friendConfirm" value="1" <?php echo set_checkbox('friendConfirm', '1'); ?> />I confirm that I know the person I am recommending above.</label>
<input type="submit" value="Submit Recommendation" />
</form>
<img src="<?=base_url(); ?>images/uploads/<?php echo $images[0]["image_filename"]; ?>" alt="<?php echo $images[0]["image_alt"]; ?>" width="180px" height="300px" class="floatRight" />
</div>
<p class="elevenFont">* Get £50 of Marks & Spencer vouchers per company or person recommended who goes on to open an account with xxxxx.</p>
</div>
<?php include("/home/xxxxx/libraries/application/views/widgets/newsWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/twitterWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/quickViewWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/fbLikePageWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/getQuoteBarWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/newsletterSubscribeWidget.php"); ?>
Controller:
<?php
class Pages extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('pages_model');
}
public function view($page = 'home')
{
if ( ! file_exists('/home/urbanfea/libraries/application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = $this->pages_model->getTitle($page);
$data['showcase'] = $this->pages_model->getShowcase();
$data['news'] = $this->pages_model->getNewsWidgetContent();
$data['quote'] = $this->pages_model->getQuoteFromBank();
$data['images'] = $this->pages_model->getPageImageArray($page);
$data['PageStraplines'] = $this->pages_model->getStraplines($page);
$data['serverStatus'] = $this->pages_model->getIssue("1");
if($page == "support")
{
$this->load->view('templates/supportHead', $data);
}
else
{
$this->load->view('templates/head', $data);
}
if($page == "recommend" || $page == "contact-us" || $page == "support")
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('friendName', 'Friend\'s Name', 'required');
$this->form_validation->set_rules('friendEmail', 'Friend\'s Email Address', 'required');
$this->form_validation->set_rules('customerName', 'Customer\'s Name', 'required');
$this->form_validation->set_rules('customerEmail', 'Customer\'s Email Address', 'required');
//$this->form_validation->set_rules(FriendConfirm', 'Confirm you know the person', 'required');
if ($this->form_validation->run() === true)
{
$this->load->view('templates/formSuccess', $data); echo "a";
}
elseif($this->form_validation->run() === false && validation_errors() != "")
{
$this->load->view('templates/formError', $data); echo "b";
}
elseif($this->form_validation->run() === false)
{
echo "c";
}
}
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
?>
Edit
Here are the routes in my router:
$route['404_override'] = '';
$route['user/(:any)'] = 'user/view/$1';
$route['user'] = 'user/login';
$route['our-work/(:any)'] = 'our_work/view/$1';
$route['our-work'] = 'our_work';
$route['what-we-do/(:any)'] = 'what_we_do/view/$1';
$route['what-we-do'] = 'what_we_do';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
Your form_open function echo form_open('recommend', array('id' => 'recommendForm')); will create the following output: <form method="post" accept-charset="utf-8" action="http:/example.com/index.php/recommend" />
This is looking for a controller called recommend, which I don't think is what you want. Change the form_open function so it directs your form to the proper controller/action.
Also, it doesn't look like your code is taking full advantage of the MVC framework. Instead of handling passing everything through the same controller/function and having all those if statements to load different views based on what $page is, you should have separate functions for each of those views.
EDIT:
Your form input elements are missing the name attribute. They must have the name attribute to be accessible through $_POST. Take a look at this page in the Codeigniter help. Maybe make use of the form_input function to generate the input fields?
Related
I need a little help with PHP sessions or something similar from someone who is well versed in PHP sessions, and who has an understanding for someone who is not.
Somebody told me that it can be done with PHP sessions or that is not possible? There are some answers that can be done with Ajax but my question is - Can it be done with PHP sessions and how? Well, everything works for me - it inserts data into the database and throws out validation errors, but this is my problem: I'm doing MVC and I don't want to refresh my page after the submission so that the user has to scroll down to see validations (because I have $msg and $errors in footer), so I want the viewport to be in the same place after the submit where the messages are written - in footer. I would be very grateful if someone can see and give me a concrete answer of what I need where to put or from where what to delete. I believe the little thing is in the Controller.
P.S. Here are 1. index.php (pijaca.php) page composed of parcels, 2. pijaca-footer.php on which the form is located, 3. routes.php on which it goes from the form and 4. Controller.php.
I tried everything: putting "id" in the form and than call it from Controller - doesn't work, looked for advice and answers on the net, I probably googled something bad (it will come with time as well as experience), but I couldn't manage. Thanks in advance!
<?php
$ime = isset($ime)?$ime:"";
$prezime = isset($prezime)?$prezime:"";
$telefon = isset($telefon)?$telefon:"";
$errors = isset($errors)?$errors:[];
session_start();
?>
<?php include'pijaca-nav.php'; ?>
<?php include'pijaca-header.php'; ?>
<?php include'pijaca-about.php'; ?>
<?php include'pijaca-photo-1.php'; ?>
<?php include'pijaca-story.php'; ?>
<?php include'pijaca-photo-2.php'; ?>
<?php include'pijaca-features.php'; ?>
<?php include'pijaca-footer.php'; ?>
<footer id="contact" class="footer">
<div class="footer__box">
<form action="routes.php" id="form" class="form" method="post">
<input type="text" class="form__input" name="firstname" placeholder="First Name" value="<?php echo $ime ?>"><span>*<?php if(array_key_exists('firstname', $errors)) echo $errors['firstname'] ?></span>
<input type="text" class="form__input" name="lastname" placeholder="Last Name" value="<?php echo $prezime ?>"><span>*<?php if(array_key_exists('lastname', $errors)) echo $errors['lastname'] ?></span>
<input type="text" class="form__input" name="telephone" placeholder="Telephone No." value="<?php echo $telefon ?>"><span>*<?php if(array_key_exists('telephone', $errors)) echo $errors['telephone'] ?></span>
<button class="btn btn--green btn--form" type="submit" name="page" value="contactus">Contact us</button>
</form>
<h5 class="heading-5 heading-5--footer-box-1">
<?php if(isset($msg)) echo $msg ?>
</h5>
</div>
</footer>
<?php
require_once'../controller/Controller.php';
$controller = new Controller();
$pageGet = isset($_GET['page'])?$_GET['page']:"index";
$pagePost = isset($_POST['page'])?$_POST['page']:"index";
$page = ($pageGet != "index")?$pageGet:$pagePost;
switch ($page) {
case 'contactus':
$controller->contactus();
break;
}
<?php
require_once'../model/DAO.php';
class Controller{
public function contactus() {
$ime = isset($_POST['firstname'])?$_POST['firstname']:"";
$prezime = isset($_POST['lastname'])?$_POST['lastname']:"";
$telefon = isset($_POST['telephone'])?$_POST['telephone']:"";
$errors = [];
if (empty($ime)) {
$errors['firstname'] = "Please enter your name";
}
if (empty($prezime)) {
$errors['lastname'] = "Please enter your lastname";
}
if (empty($telefon)) {
$errors['telephone'] = "Please enter your telephone";
} else {
if (preg_match('/^[0-9 +_-]*$/', $telefon)) {
} else {
$errors['telephone'] = "Please enter a number";
}
}
if (count($errors) == 0) {
$dao = new DAO();
$podacikorisnika = $dao->korisnik($ime, $prezime, $telefon);
$msg = "Sucsses!";
include 'pijaca.php';
} else {
$msg = "Please enter all fileds";
include 'pijaca.php';
}
}
}
please help me... My controller for registration and login is not working. Whenever I input the data in either login or register it will back to register and login view and not the index/home nor the data that I input enter mysql.
I create it like when I success in inputting the data on register it will direct to login then when you login it will direct to home. Other is login, when I login it will direct to home if it can login.
Controller: Member.php
class Member extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function index() {
$this->load->view('front/login');
}
public function Login() {
$this->load->view('front/login');
}
public function Register() {
$this->load->view('front/register');
}
public function profile() {
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error","Please login first to view");
redirect('Member/Login');
}
$this->load->view('front/home');
}
}
Controller: Register.php
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function registerMember() {
//validate the data taken through the register form
$this->form_validation->set_rules('username','Username','required|is_unique[member.username]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5|min_length[6]');
$this->form_validation->set_rules('conf_password', 'Confirm Password', 'trim|required|min_length[6]|matches[password]');
if ($this->form_validation->run() == TRUE) {
//load the model to connect to the db
$this->load->model('Member_model');
$this->Member_model->insertMember();
//set message to be shown when registration is completed
$this->session->set_flashdata('success','You are registered!');
redirect('Member/Login');
} else {
$this->load->view('front/register');
}
}
}
Controller: Login.php
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function loginMember() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('front/login');
} else {
$this->load->model('Member_model');
$reslt = $this->Member_model->checkLogin();
if ($reslt != false) {
//set session
$username = $_POST['username'];
$password = sha1($_POST['password']);
//fetch from databse
$this->db->select('*');
$this->db->from('member');
$this->db->where(array('username' => $username , 'password' => $password));
$query = $this->db->get();
$member = $query->row();
//if use exists
if ($member->username) {
//login message
$this->session->set_flashdata("success","You are logged in");
//set session variables
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $member->username;
//redirect
redirect('Member/profile','refresh');
}
} else {
//wrong credentials
$this->session->set_flashdata('error','Username or Password invalid!');
redirect('Member/Login');
}
}
}
//logging out of a user
public function logoutMember() {
unset($_SESSION);
redirect('Member/Login');
}
}
Model: Member_model.php
class Member_model extends CI_Model {
public function insertMember () {
//insert data
$data = array(
//assign data into array elements
'username' => $this->input->post('username'),
'email' =>$this->input->post('email'),
'password' => sha1($this->input->post('password'))
);
//insert data to the database
$this->db->insert('member',$data);
}
public function checkLogin() {
//enter username and password
$username = $this->input->post('username',TRUE);
$password = sha1($this->input->post('password',TRUE));
//fetch data from database
$this->db->where('username',$username);
$this->db->where('password',$password);
$res = $this->db->get('member');
//check if there's a user with the above inputs
if ($res->num_rows() == 1) {
//retrieve the details of the user
return $res->result();
} else {
return false;
}
}}
View:
Register.php
<body class="background-login">
<div class="main-w3layouts wrapper">
<h1> SignUp </h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form method="post" action="<?php echo site_url('register/registerMember'); ?>" >
<input class="text" type="text" id="username" name="username" placeholder="Enter a username">
<input class="text email" type="email" id="email" name="email" placeholder="Enter your email">
<input class="text" type="password" id="password" name="password" placeholder="Enter a password">
<input class="text w3lpass" type="password" id="conf_password" name="conf_password" placeholder="Confirm your password">
<div class="wthree-text">
<label class="anim">
<input type="checkbox" class="checkbox" required="">
<span>I Agree To The Terms & Conditions</span>
</label>
<div class="clear"> </div>
</div>
<input type="submit" value="SignUp">
</form>
<p>Already have an Account? Login Now!</p>
</div>
</div>
Login.php
<body class="background-login">
<div class="main-w3layouts wrapper">
<h1> SignIn </h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form method="post" action="<?php echo site_url('Login/loginMember'); ?>" >
<input class="text" type="text" id="username" name="username" placeholder="Your username"><br>
<input class="text" type="password" id="password" name="password" placeholder="Your password">
<input type="submit" value="Login"/>
</form>
<p>Don't have an Account? SignUp NOW!</p>
</div>
</div>
I even chop my code into part like this, but the problem still the same... Is just like the if form_validation->run is not running and just got cut to else...
So the problem is:
When I input data it will not enter the data or redirect to another page.
*register -> it will direct to register after i submit the data
What I want is when I submit the data it will direct to login.
*login -> it will direct to login after i submit the data
What I want is when I submit the data it will direct to home.
-> result ->
I also had this case . I solved it by passing $this in to run()
if ($this->form_validation->run($this) == TRUE)
You can pass array in where condition in checkLogin function
$where_array = array('username' => $username,'password' => $password);
$this->db->where($where_array);
$res = $this->db->get('member');
Hope it help you too!
You can not use the form_open function and html form tag at the same time, so remove anyone from it and pass the whole path in the action.
If you use form_open function then please add the form_close function.
in your register and login view
<?= form_open() ?>
<form action="#" method="post">
you added this. this is wrong.at a same time you open two form you need to remove a line.and add some action to form for example
<form action="<?= base_url('yourControllerName/YourMethodname')?>" method='post'></form>
and second thing in Member.php Controller you added this line
if ($this->form_validation->run() === FALSE){
Some code
}
this is wrong you need this
if ($this->form_validation->run() == FALSE)
please check and ping me......
Make sure your base_url in config.php is not null.
In register.php remove <?=form_open('member/login')?> and <?= form_close() ?>
Instead add, <form method="post" action="<?php echo site_url('Member/register'); ?>" >
and
</form>
redirect your page:
//login
if ($this->form_validation->run() === TRUE)
{
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$user= $this->member_model->create_user();
if($user >0){
redirect('front/home');
} else {
redirect('front/login');
}
}
you can same as in singup
My codeigniter validation errors are not displaying someone can help?
my code is
public function addProduct(){
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
if (!$this->form_validation->run() == FALSE)
{
// some stuff on validation success
}
else{
$this->load->view('product/addProduct');
}
}
and i have added
echo validation_errors(); in my view and action of the form is product/addProduct.
Try this it's work for you.
form_error() function return your form error.
$post_fields = $this->input->post();
$data['msg'] = '<ul>';
foreach ($post_fields as $k => $v) {
if (form_error($k))
$data['msg'] .= "<li>" . strip_tags(form_error($k)) . "</li>\n";
}
$data['msg'].='</ul>';
$this->load->view('product/addProduct',$data);
OR
echo validation_errors();//this function also return form error.
On view example
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<!-- lower case for the controller name on form open -->
<?php echo form_open_multipart('product/addProduct');?>
<h5>productName</h5>
<input type="text" name="productName" value="<?php echo set_value('productName'); ?>" size="50" />
<h5>productPrice</h5>
<input type="text" name="productPrice" value="<?php echo set_value('productPrice'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close();?>
Controller
Make sure your file name and class name is something like this below where first letter only upper case
Guide
Filename: Product.php
<?php
class Product extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->helper('url');
}
public function addProduct(){
// You can get data from here also
$this->data['some'] = 'Blah';
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
// remove your !
if ($this->form_validation->run() == FALSE){
// You can just display view in this area you do not have to load it multiple times
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
} else {
// some stuff on validation success
}
}
}
Also check you have set your base url in config.php is required now in CI3 versions.
I'm new to Codegniter so go easy on me. I'm building a simple login form and I have successfully redirected to a page when the login credentials are correct. However, if I submit an empty form I get no error messages. I'm also using set_value in the form field and codeigniter does not refill what the user inputted once the form is submitted. Somehow that data is being cleared. Here are a few things i've done for clarity sake.
Auto-loaded the form_validation library
Auto-loaded form helper
Echoed validation_errors above form
account.php (controller)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('User_model', 'user');
}
public function index() {
$this->load->view('home');
}
public function validate() {
$this->form_validation->set_rules('username', 'username', 'xss_clean|required');
$this->form_validation->set_rules('password', 'password', 'xss_clean|required|md5');
$user_data = array(
'username' => $this->input->post('username'),
'password' => MD5($this->input->post('password'))
);
if ($this->form_validation->run() == FALSE)
{
$data['title'] = "Login Fool";
$this->load->view('templates/header', $data);
$data['contents'] = $this->load->view('login_view', $data, TRUE);
$this->load->view('page', $data);
$this->load->view('templates/footer');
}
else
{
$validated = $this->user->validate($user_data['username'], $user_data['password']);
if($validated){
redirect(base_url() . 'account');
}
else{
$this->session->set_flashdata('LoginError', 'Sorry, your credentials are incorrect.');
redirect(base_url() . 'account/login');
}
}
}
public function login() {
$data['title'] = "Login Fool";
$this->load->view('templates/header', $data);
$data['contents'] = $this->load->view('login_view', NULL, TRUE);
$this->load->view('page', $data);
$this->load->view('templates/footer');
}
}
login_view.php (view)
<h1>Login Now</h1>
<?php
if(validation_errors() != false) {
echo "<div id='errors'>" . validation_errors() . "</div>" ;
}
?>
<?= ($this->session->flashdata('LoginError')) ? '<p class="LoginError">' . $this->session->flashdata('LoginError') . '</p>' : NULL ?>
<?php echo form_open('account/validate'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username" value="<?php echo set_value('username'); ?>"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="passowrd" name="password" value="<?php echo set_value('password'); ?>"/>
<br/>
<input type="submit" value="Login"/>
</form>
Any ideas why the errors won't show above the form?
Turns out my model was the culprit. It was extending CI_Controller not CI_Model. Thanks to everyone who took a look at this. This code works.
Controler
//class News
public function update($slug)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['news_item']=$this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
//$this->load->view('save',$save);
$this->load->view('templates/footer');
}
Model new_model.php
//class News_model
public function get_news($slug = FALSE)
{
if($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news',array('slug'=>$slug));
return $query->row_array();
}
public function update_news($slug)
{
$query=$this->db->where('slug', $slug);
$this->db->update('news' ,$query);
return $query->row_array();
}
in update.php view file code given below..
view update.php file
<h2>Update New Item</h2>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $news_item['title']; ?>" readonly/><br>
<label for="text">Text</label>
<textarea name="text" cols="35" rows="16"><?php echo $news_item['text'];?></textarea><br>
save
</form>
data will be fetch but problemb is that when i click on "save" link page not found error generatos why?
how can call this view save.php file..
Change
save
to
<input type="submit" value="save" />
Here you have used link in-place of submit button.
When you use submit button it will post/get data on url that is there in the form action.
Here you can use :
<?php echo form_submit('mysubmit', 'Submit Post!'); ?>
It will produce...
<input type="submit" name="mysubmit" value="Submit Post!" />
For more details : Form Helper