codeigniter session user_data being reset - php

I am using Codeigniter database session. I have a search navigation on the header of my page which contains a search from and to date and a text field.
I also have pagination on the page. I am using a custom controller (MY_Controller) and I am setting the from and to dates here. See below.
public function __construct()
{
parent::__construct();
$this->load->model('News_model');
$this->set_dates();
}
function set_dates()
{
if (empty($this->input->post('from_date')))
{
$this->session->set_userdata('sel_from_date', date('Y-m-d'));
}
else
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$this->session->set_userdata('sel_from_date', $this->input->post('from_date'));
}
}
if (empty($this->input->post('to_date')))
{
$this->session->set_userdata('sel_to_date', date('Y-m-d'));
}
else
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$this->session->set_userdata('sel_to_date', $this->input->post('to_date'));
}
}
}
This works fine even when I enter dates in the from and/or to fields and click submit, the correct dates stay in the search fields.
However when I click on the link for the next page (in pagination) which basically adds another segment to the URL (i.e. mysite/news/politics/1) and loads the page, the dates in the session user_data are reset. I thought maybe the logic above for blank input dates was being executed again in this instance but that is not the case.
HTML:
<div class="form-group">
<label for="from_date" class="col-sm-2 control-label">From Date:</label>
<div class="col-sm-6">
<input type="text" placeholder="From Date" class="form-control" name="from_date" id="from_date" width=10" value="<?php echo $this->session->userdata('sel_from_date'); ?>" />
</div>
</div>
<div class="form-group">
<label for="to_date" class="col-sm-2 control-label">To Date:</label>
<div class="col-sm-6">
<input type="text" placeholder="To Date" class="form-control" name="to_date" id="to_date" value="<?php echo $this->session->userdata('sel_to_date'); ?>" />
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
<button type="submit" class="btn btn-default" name="go" id="go">Go</button>
</div>

Check whether the session variable 'sel_from_date' is already set .
If yes don't set it again. Try below in your controller:
if($this->session->userdata('sel_from_date') != '')
{
// Do not set the session variable 'sel_from_date'
}
else
{
// Execute the function $this->set_dates()
}

I resolved the issues with the following code.
if (empty($this->input->post('from_date')) && !$this->session->userdata('sel_from_date'))
{
....
}

Related

Redirect page on particular error when validation failed in CodeIgniter

I am creating single page website which have different sections and one of then is signup page, When i submit form without entering values then it shows errors but page does not load on that section, Page stuck above. I want when validation fails then page need to redirect on that particular error.
Example: If I did not fill firstname but filled lastname then page need to redirect on firstname directly.
// Controller
if($this->form_validation->run() == false)
{
$data=array();
$base = array();
$data['whatsinside']=$this->load->view(codeg_front_version('whatsinside'), '', true);
$data['signup']= $this->load->view(codeg_front_version('signup'), '', true);
$base['custom'] = 'home';
codeg_base($data,$base,true,true,true);
}
else
{
Redirect to thank you page
}
View
<div class="form-group col-md-6">
<label class="form-control-placeholder" for="fname">First Name</label>
<input type="text" id="fname" name="fname" class="form-control form-text" value="<?=set_value('fname')?>" required />
<div class="error-msg"><?php echo form_error('fname'); ?></div>
</div>
<div class="form-group col-md-6">
<label class="form-control-placeholder" for="lname">Last Name</label>
<input type="text" id="lname" name="lname" class="form-control form-text" value="<?=set_value('lname')?>" required />
<div class="error-msg"><?php echo form_error('lname'); ?></div>
</div>
<div class="form-group col-md-6 clear">
<label class="form-control-placeholder" for="pnric">NRIC</label>
<input type="text" id="pnric" name="pnric" class="input-nric form-control form-text" value="<?=set_value('pnric')?>" maxlength="9" required />
<div class="error-msg"><?php echo form_error('pnric'); ?></div>
</div>
<div class="form-group col-md-6 gender">
<label class="col-md-2 gsb-label-light" for="pnric">Gender</label>
<div class="col-md-10">
<div class="row">
<label class="gsb-radios">Male
<input class="form-check-input gsb-radio" type="radio" name="gender" id="male" value="Male" <?php echo set_radio('gender', 'Male'); ?> />
<span class="checkmark"></span>
</label>
<label class="gsb-radios">Female
<input class="form-check-input gsb-radio" type="radio" name="gender" id="female" value="Female" <?php echo set_radio('gender', 'Female'); ?> />
<span class="checkmark"></span>
</label>
</div>
</div>
<div class="error-msg clear"><?php echo form_error('gender'); ?></div>
when come to the fail condition then redirect to same page but on particular error.
You need something like this:
// check form validation only on POST action
if ($this->input->post('submit') == 'save') {
if ($this -> form_validation -> run() == TRUE) {
// form is valid
// save data and redirect to thank you page
redirect('thank_you_page');
} else {
// we have errors
// redirect to specific page section
redirect('same_page#error_section');
}
}
You need to have the action button like this:
<button type="submit" name="submit" value="save">
Save
</button>
Edit 2
On validation error, you need to get first invalid input and redirect this specific input id
// check form validation only on POST action
if ($this->input->post('submit') == 'save') {
if ($this -> form_validation -> run() == TRUE) {
// form is valid
// save data and redirect to thank you page
redirect('thank_you_page');
} else {
// we have errors
// redirect to specific error section
// get first error element
$ordered_required_inputs = array(
'fname', 'lname', 'pnric'
);
$section_err = '';
foreach ($ordered_required_inputs as $key => $input_name) {
if (form_error($input_name) != ''){
$section_err = '#'.$input_name;
break;
}
}
redirect('same_page'.$section_err);
}
}
Edit 3
Please take into consideration that after redirection, set_value will not work because set_value requires that the form validation ran in the same context... you lose this context when you redirect.
To go to the specific input section without lose the previously entered data, you need to use client side validation instead of server side validation. This jQuery Validation Plugin will help you to make validation before submitting the page.

stop duplicate entry after reload browser

I have a form and trying to insert data in table with class. Data is inserting in proper way.
But when click on browser reload after insert query, then it inserts duplicate entry in table.
I tried it with redirect function. But not working.
My form is:
<?php
if(isset($_POST['insertcourse']))
{
$userprofileobj->insert_course($_POST['c_name'],$_POST['c_description']);
}
?>
<form action="" method="POST">
<div class="control-group">
<label class="control-label">Course Name :</label>
<div class="controls">
<input type="text" class="span11" placeholder="First name" name="c_name" />
</div>
</div>
<div class="controls">
<label class="control-label">Course Description :</label>
<textarea class="textarea_editor span12" rows="6" placeholder="Enter text ..." name="c_description"></textarea>
</div>
<div class="form-actions">
<input type="submit" value="SAVE" name="insertcourse" class="btn btn-success">
</div>
</form>
My classes.php is:
<?php
class operations{
public $user_name;
public $error;
public $con;
public function __construct()
{
$this->con = new mysqli("localhost","root","","admin_with_oops");
}
public function insert_course($c_name,$c_description)
{
$date1 = date("Y-m-d");
$result = $this->con->query("insert into courses (c_name,c_description,date1,status1) VALUES ('$c_name', '$c_description', '$date1','1')");
if($result)
{
$alertmsgs = "Inserted Successfully";
$this->alertmsg($alertmsgs);
}
}
public function alertmsg($alertmsgs)
{
echo"<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong></strong> $alertmsgs </div>
</div>";
}
}
You could generate a guid and put it in a hidden input in your form. Database that ID on the initial submit and don't allow it to be inserted a second time.
<input type="hidden" value="<?php com_create_guid() ?>">
It's a little more foolproof than post-redirect-get and will be a less jarring user experience, especially over high latency networks.

Show custom error message

I'm trying to show errors in form validation.
But these messages are always visible.
<form name="user-form" method="POST" action="{{route('registrationUser')}}">
<div class="col-lg-8">
Логин <input type="text" name="log" ng-model="mobile" required pattern="[a-zA-Z ]*"><br>
<span class="help-block" ng-show="errors.log[0]"><p>Только английский</p></span>
</div>
Пароль <input type="text" name="pass" ng-minlength="8" ng-pattern="regex" required pattern="[a-zA-Z]{8,32}" ><br>
<div ng-show="user-form.pass.$error.pattern">Name doesn't match pattern!</div>
<button ng-click='SaveUser()' name="Регистрация">Регисрация</button>
</form>
you can add another condition to ng-show
<div ng-show="user-form.pass.$error.pattern && buttonclicked">Name doesn't match pattern!</div>
and set that condition to true in your controller
$scope.SaveUser= function () {
$scope.buttonclicked = true;
};
so error messages will be visible only when user clicks on submit button

Keep saved data in form after revisiting the page

I've created a form with three input fields. I managed to find out how to keep the data after saving the form, but when I leave the page and come back to this form, the fields are empty again.
Here is my code:
<?php
if(isset($_POST['save_home_details'])) {
$home_title = escape_string($_POST['home_title']);
$home_desc = escape_string($_POST['home_desc']);
$home_keywords = escape_string($_POST['home_keywords']);
$query = "INSERT INTO settings(home_title, home_desc, home_keywords) ";
$query .= "VALUES('{$home_title}', '{$home_desc}', '{$home_keywords}') ";
$home_details_query = mysqli_query($conn, $query);
confirm($home_details_query);
echo "<div class='alert alert-success'>Settings saved successfully!</div>";
}
?>
<form action="" method="post">
<div class="form-group">
<label for="home_title">Home title</label>
<input type="text" class="form-control" name="home_title" value="<?php if(isset($_POST['home_title'])) { echo htmlentities ($_POST['home_title']); }?>">
</div>
<div class="form-group">
<label for="home_title">Home description</label>
<input type="text" class="form-control" name="home_desc" value="<?php if(isset($_POST['home_desc'])) { echo htmlentities ($_POST['home_desc']); }?>">
</div>
<div class="form-group">
<label for="home_title">Home keywords</label>
<input type="text" class="form-control" name="home_keywords" value="<?php if(isset($_POST['home_keywords'])) { echo htmlentities ($_POST['home_keywords']); }?>">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="save_home_details" value="Save settings">
</div>
</form>
Basically what I want here is:
to be able to add value to these fields
save the values
keep the values in the fields whenever I come back to this page
if I click the save settings button, update the values and not add a new record to the database.
I know I haven't added the update query yet, but can I do that on the same page where I insert the values into the database?
Thanks
If you need to store temporarily you can use $_SESSION['anyData'] = $anyData.
When you do not need you can unset($_SESSION['anyData'])

Calling/Using PHP function in HTML

I am practicing with PHP and trying to build Validation for my HTML register form, My idea is to create PHP function for each input field within my HTML form and call it if the field has been left out empty.
Am at a stage where everything is ready but I dont know how to call my functions within HTML...
Could some one sugest a way of calling a functions withing HTML form.
session_start();
if(isset($_POST['reg'])){
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$tel = mysql_real_escape_string($_POST['telephone']);
$firstname = mysql_real_escape_string($_POST['firstname']);
}
class Validation{
public function FirstName(){
if($firstname == NULL){
echo '<p>Enter Name</p>';
}
}
public function LastName(){
if($lastname == NULL){
echo '<p>Enter \surname</p>';
}
}
public function EmailAdress(){
if ($email == NULL){
echo '<p>Enter Email</p>';
}
}
public function TelephoneNumber(){
if($tel == NULL){
echo '<p>Enter Name</p>';
}
}
}
?>
<!-- banner -->
<div class="hero-unit banner-back">
<div class="container">
<div class="row-fluid">
<div class="span8">
</div>
<div class="span4 form-back text-center">
<form name="reg" action="" method="post">
<fieldset>
<legend>Free Workshop</legend>
<div class="input-wrapper">
<input type="text" placeholder="First Name" id="firstname" name="firstname <? FirstName(); ?>"/>
</div>
<div class="input-wrapper">
<input type="text" placeholder="Last Name" id="lastname" name="lastname"/>
</div>
<div class="input-wrapper">
<input type="email" placeholder="Email Address" id="email" name="email"/>
</div>
<div class="input-wrapper telephone">
<input type="text" placeholder="Telephone number" id="telephone" name="telephone"/>
</div>
<div class="input-wrapper">
You cannot call PHP from HTML after you delivered the Website to the Browser. (well you can with AJAX, but that would be some overkill). When the user does some input to the fields the page is not sent to your server (where PHP is interpreted).
So I suggest you do the validation client side in JavaScript.
To output PHP Variables or the return of a Function call simply use the <?= myFunction() ?> syntax.

Categories