Add Variables to an array? - php

I want to add variables to an array, what I'm trying to do is to check if there is an error from the view within the controller and the variable will be added to an array here is an example.
$error = array ();
if (input1 == null)
{
$errormessage1 = '*';
$error[] = $errormessage1;
}
if (input2 == null)
{
$errormessage2 = '*';
$error[] = $errormessage2;
}
if (input1 != null AND input2 != null)
{
//insert to database or something
}
else
$this->load->view("view", $error);
The problem is that the values are not being inserted to the array. And the array is not printing anything after I return it to the view.php
Here is an example of my view.php
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
if(isset($errormessage1 ))
echo $errormessage1 ;
Thank you for any help that you can give me.

I see you are trying to tell the user that username is required. right? then why don't you utilize Codeigniter form_validation library? to display the errors you use form helper method validation_errors()
Your View
<?php echo validation_errors();
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
Your Controller
public function your_method(){
$this->load->library('form_validation');
$this->form_validation->set_rules('input1','Username','required');
//and so on for other user inputs
if($this->form_validation->run()===TRUE){
//send to model may be
}else{
$this->load->view('view');
}
}

Related

How can I keep variable value if validation fails in codeigniter

I want to validate a form to make sure a user entered something in the description field in this situation form validation is correct.
But,
Here , I pass value to function 2 by fetching values from function 1
When function 2 loads first time it fetch data and display the values (OK)
But When function 2 resubmit for validation and submision data these valitable get empoty and it throw the error Message: Undefined variable: query (ERROR)
I don't know how to do this, hehe. I'm just a newbie PHP programmer.
Here's what I have so far:
function 1
public function ask()
{
$this->load->model('MainM');
$this->load->library('form_validation');
$this->form_validation->set_rules('index', 'AL Index', 'trim|required|min_length[7]|max_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('enterindex');
}else{
$query = null; //emptying in case
$index = $this->input->post("index"); //getting from post value
$query = $this->db->get_where('tbl_reg', array('reg_index' => $index));
$count = $query->num_rows(); //counting result from query
if ($count == 1) {
$data['query'] = $this->MainM->getregdata($index);
$result = $this->load->view('submitques',$data);
}else{
$data = array();
$data['error'] = 'error';
$this->load->view('enterindex', $data);
}
}
function 2
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Actully you have $data variable put in else part so thats why this error appeared you need to define before loop.
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
// define here before check condtions
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
If you wish to use the posted $data variable on false condition, you could moving it up outside the validation block :
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Try with This Code:
First Add Form Library to config/autoload.php
$autoload['libraries'] = array('database','form_validation');
html Code
This is view file login.php
<?php echo form_open('action_controller_name', array('class' => '', 'enctype' => 'multipart/form-data', 'role' => 'form', 'name' => 'myform', 'id' => 'myform')); ?>
<div class="form-group">
<label class="control-label" for="mobile">Mobile-No</label>
<input type="text" name="mobile" value="" placeholder="Enter Mobile No" id="mobile" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<div class="form-group">
<label class="control-label" for="password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="password" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<input type="submit" value="Login" class="btn btn-gray" id="submit" />
<a class="forgotten" href="<?php echo base_url('login/forgot_password'); ?>" style="font-size: 13px;">Forgot Password</a>
<?php
echo form_close();
?>
My Action Controller
public function action_controller_name() {
$this->load->helper(array('form')); // Load Form Library
$this->load->library('form_validation'); // Load Form Validaton Library
$this->form_validation->set_rules('mobile', 'mobile', 'required', array('required' => 'Please Enter Mobile Number.'));
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'Please Enter passsword.'));
if ($this->form_validation->run() === TRUE) { // Check validation Run
// Your Login code write here
} else {
$this->load->view('login', $this->data);
}
}
Try this code.You can keep variable value if validation fails in codeigniter successfully.

Not able to retain values after unsuccessful submission of form in codeigniter

I want that in case a form is not submitted properly then the values that had been entered by the user should not get lost. The form is built in codeigniter
View
<?php echo form_open_multipart('user/add_data'); ?>
<?php
$data = array(
'type'=>'text',
'name'=>'name',
'class'=>'form-control',
'required' => 'required',
'value' => set_value('name')
);
?>
<?php echo form_input($data); ?>
<?php
$data = array(
'type'=>'file',
'name'=>'userfile',
'class'=>'fileinput btn-info',
'id'=>'filename3',
'data-filename-placement'=>'inside',
'style' => 'margin-left: 330px',
'title'=>'If any document upload here (* XLS | DOC | PDF | DOCX | XLSX )'
);
echo form_upload($data);
?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn btn-primary pull-right',
'name'=>'submit',
'content'=>'Submit'
);
echo form_button($data);
?>
<?php echo form_close(); ?>
Controller
public function add_requirement_data() {
$config['upload_path'] = './request/';
$config['allowed_types'] = 'xls|xlsx|doc|docx|pdf';
$config['max_size'] = 9000000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
if ($data['upload_data']['file_size'] == '0')
{
$this->session->set_flashdata('req_msg', 'Cannot Upload Empty File');
redirect('user/requirement');
}
else
{
if ($this->um->create_requirement_nofile($instanthire_main_id))
{
$this->session->set_flashdata('req_msg', 'Requirment raised successfully');
redirect('user/requirement');
}
}
}
}
Can anyone please tell how to retain values in codeigniter form
By using sessions
Let us consider your name input tag
In your view
<?php
$data = array(
'type'=>'text',
'name'=>'name',
'class'=>'form-control',
'required' => 'required',
'value' => $this->session->userdata('name')
);
?>
And in your controller,
$this->session->set_userdata('name',$this->input->post('name'));
if ($data['upload_data']['file_size'] == '0')
{
$this->session->set_flashdata('req_msg', 'Cannot Upload Empty File');
redirect('user/requirement');
}
else
{
if ($this->um->create_requirement_nofile($instanthire_main_id))
{
$this->session->unset_userdata('name');
$this->session->set_flashdata('req_msg', 'Requirment raised successfully');
redirect('user/requirement');
}
}

Codeigniter Hidden Form Becomes NULL

I've got a really weird issue that I can't seem to figure out or understand. So essentially I have a to grab the ID passed through the Codeigniter URI, have it populate a hidden form, and then submitted. However when I submit the form as hidden, it comes back saying the data is NULL. I have tried and changed it to form_input and it works fine. Can anyone help me or explain to me why this is the case?
I have tried the following solutions.
URL
http://localhost/list/players/add/1/
where I want URI 3 ('1') to pass on to the form and submitted.
Solution 1 - Having the URI pass straight to data array
Controller
function add() {
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$league_id = $this->uri->segment(3);
$data = array(
'leagues_id' => $league_id,
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
Solution 2 - Grabbing the URI and fill a hidden form
Controller
function add() {
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open('players/add/');
?>
<?php
echo "<br>";
echo "<br>";
echo "League Name";
echo "<br>";
foreach ($leagues_list->result() as $row) {
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
$data = array( 'name' => 'leagues_id',
'value' => $league_id,
);
echo form_hidden($data);
}
echo "<br>";
echo "<br>";
$data = array( 'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
In both scenarios, on submit it comes back with an error saying leagues_id is NULL. Now I have tried in Solution 2 to change from 'form_hidden' to 'form_input' and straight away clicking submit and it works fine.
Can anyone help me or advise why this is the case?
Many thanks.
If you want to add a parameter to your controller's function, you have to add it to: function func($parameter = 0) (= 0 is optional for default value).
In this case you can access the parameter by $parameter.
In your View file, you can open your form to post to the current url. For this you need to load the url helper in your controller: $this->load->helper('url'); (or you can autoload it in application/autoload.php).
Your form_hidden declaration was bad too. If you want to declare it with array(), then you have to use this syntax:
$data = array(
'name' => 'John Doe',
'email' => 'john#example.com'
);
echo form_hidden($data);
// Would produce:
<input type="hidden" name="name" value="John Doe" />
<input type="hidden" name="email" value="john#example.com" />
More information on Form helper: https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
For the right solution, try this:
Controller
function add($league_id = 0)
{
if($league_id != 0)
{
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE)
{
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
}
else
{
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data))
{
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open(current_url());
echo "<br /><br />";
echo "League Name <br />";
foreach ($leagues_list->result() as $row)
{
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
echo form_hidden('leagues_id', $league_id);
}
echo "<br /><br />";
$data = array(
'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn'
);
echo form_submit($data);
echo form_close();
?>

Get data from $_SESSION

I'm trying to create simple server side validation, this is my method
public function create() {
$name = $_POST['name'];
session_start();
unset($_SESSION['errors']);
$count = $this->model->checkIfUserExists($name);
if($count > 0) {
$_SESSION['errors'] = array(
'message' => 'User Already Exists',
'variables' => array(
'name' => $_POST['name'],
'password' => $_POST['password'],
),
);
header('location: ' . URL . 'user/registration');
exit;
}
$data = array();
$data['name'] = $_POST['name'];
$data['password'] = $_POST['password'];
$this->model->create($data);
header('location: ' . URL);
}
and below code from registration.php
<?php
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>
but I got errors
Warning: Illegal string offset 'message' in C:\xampp\htdocs\test\views\user\registration.php on line 6
�
Notice: Undefined index: message in C:\xampp\htdocs\test\views\user\registration.php on line 6
How to fix it?
Generally, Warning: Illegal string offset ... means that you are trying to access a string as an array.
Currently, you are setting $_SESSION['errors'] to an associative array with two elements, message and variables. I believe what you are trying to achieve is to create an array with multiple errors that each have a message and variables.
Setting it like this should do:
...
$_SESSION['errors'] = array();
if ($count > 0) {
$_SESSION['errors'][] = array(
'message' = > 'User Already Exists',
'variables' = > array(
'name' = > $_POST['name'],
'password' = > $_POST['password'],
),
);
header('location: '.URL.'user/registration');
exit;
}
...
The empty square brackets add a new element to the array:
$myArray[] = $myNewElement;
This way you can easily add additional errors to the list:
$_SESSION['errors'][] = array(
'message' = > 'Error two',
'variables' = > array(...),
);
$_SESSION['errors'][] = array(
'message' = > 'Error three',
'variables' = > array(...),
);
It's because foreach goes throught items in main array. ["message", "variables"]
Assign $_SESSION['errors'] = like this: $_SESSION['errors'][] =
$_SESSION['errors'][] = array(
'message' => 'User Already Exists',
'variables' => array(
'name' => $_POST['name'],
'password' => $_POST['password'],
),
);
registration.php at first start session session_start()
<?php
session_start();
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>

Echoing post value

I'm trying to figure out why its echoing the $bookingDate. I don't have any echo or print statements going on in my code so its hard to understand why its echoing in the response console. I'm hoping there will be someone to see what's causing this issue.
function submitBooking()
{
$outputArray = array('error' => 'yes', 'message' => 'unproccessed');
$outputMsg = '';
// Sets validation rules for the login form
$this->form_validation->set_rules('eventName', 'Event Name',
'is_natural_no_zero');
$this->form_validation->set_rules('label', 'Label',
'is_natural_no_zero');
$this->form_validation->set_rules('bookingDate', 'Booking Date',
'required');
$this->form_validation->set_rules('location', 'Location',
'required');
$this->form_validation->set_rules('arena', 'Arena',
'is_natural_no_zero');
$this->form_validation->set_rules('introduction', 'Introduction',
'required');
// Checks to see if login form was submitted properly
if (!$this->form_validation->run())
{
$outputArray['message'] =
'There was a problem submitting the form! Please refresh the window and try again!';
}
else
{
$bookingDate = $this->input->post('bookingDate');
$bookingDate = date("d-m-Y h:i:s", strtotime($bookingDate));
if ($this->eventsmodel->bookEvent($this->input->post('eventName'), $this->input->post('label'), $bookingDate, $this->input->post('location'), $this->input->post('arena'), $this->input->post('introduction')))
{
$outputArray = array('success' => 'Yes', 'message' =>
'The event was booked successfully!');
}
else
{
$outputArray['message'] =
'The event was not booked! Please try again later!';
}
}
echo json_encode($outputArray);
}
Look in for an echo statement in eventsmodel->bookEvent. You might be echoing the $bookingDate there. here is everything fine.
Hope this helps.

Categories