Echoing post value - php

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.

Related

Codeigniter blog application bug: form is loaded without validation errors

I am working on a blog application in Codeigniter 3.1.8 and Bootstrap 4. I have an "Edit post" form with validation.
If validation fails (because the Title field has been emptied, for example), the form should reload with validation errors.
My update() (lives in the Posts controller) method is wrong: it uses a redirect, so the form is reloaded without validation errors, to its initial state.
public function edit($id) {
// Only logged in users can edit posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
$data['post'] = $this->Posts_model->get_post($id);
if ($this->session->userdata('user_id') == $data['post']->author_id) {
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit-post');
$this->load->view('partials/footer');
} else {
/* If the current user is not the author
of the post do not alow edit */
redirect('/' . $id);
}
}
public function update() {
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
$id = $this->input->post('id');
// Update slug (from title)
if (!empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
redirect('/posts/edit/' . $slug);
}
}
I am almost certain the problem is this line: redirect('/posts/edit/' . $slug); but I have not been able to find a viable alternative.
Using $this->edit($id) instead of redirect('/posts/edit/' . $slug); does not work either. I wish it would, because I want to keep the code DRY.
What shall I change?
Edit. I did this:
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$this->form_validation->run();
$this->session->set_flashdata('errors', validation_errors());
var_dump($this->session->flashdata('errors'));
//redirect('/posts/edit/' . $slug);
}
The var_dump($this->session->flashdata('errors')); returns all the validation errors.
I wish to add the class has-error to the form-group and append <p class="error-message">The Title field is required.</p>.
<div class="form-group has-error">
<input type="text" name="title" id="title" class="form-control error" placeholder="Title" data-rule-required="true" value="Learn to code with us" aria-invalid="true">
<p class="error-message">The Title field is required.</p>
</div>
You have 3 options:
Use flash data in update method on failure (you are already using it on success). Simply assign the errors to a flash data variable and get it after you redirect back to edit.
Combine edit and update methods (most common for non-ajax usage).
Use ajax and return json encoded strings for errors or success messages.
Option 2:
This option also solves the potential authentication issue pointed out in the comments.
Please read the comments embedded in the code.
public function edit($id) {
// Only logged in users can edit posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data['post'] = $this->Posts_model->get_post($id);
if ($this->session->userdata('user_id') == $data['post']->author_id) {
show_error('Access denied'); // function exits
}
if ($_POST) {
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
//$id = $this->input->post('id'); not required anymore
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if ($this->form_validation->run() && $this->upload->do_upload()) {
// always use the name from the upload lib
// sometimes it changes it in case of duplicates (read docs for more)
$post_image = $this->upload->data('file_name');
// doesn't make sense with title validation rule, this will always be true to get
// passed validation
if (!empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug . "-" . $slugcount;
}
} else {
$slug = $this->input->post('slug');
}
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$data['errors'] = validation_errors() . $this->upload->display_errors();
}
}
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->sidebar_posts($limit = 5, $offset = 0);
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit-post');
$this->load->view('partials/footer');
}
What I would do in this scenario is merge both methods into a single method relying on the validation to know if I am saving the entry or not.
your code would look something like this:
public function edit($id) {
// Only logged in users can edit posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$Post = $this->Posts_model->get_post($id);
// user does not own the post, redirect
if ($this->session->userdata('user_id') !== $Post->author_id) {
redirect('/' . $id);
}
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
// if validation fails, or the form isn't submitted
if ($this->form_validation->run() === false ) {
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
$data['post'] = $Post;
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit-post');
$this->load->view('partials/footer');
}else{
// Update slug (from title)
if (! empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
}
}
and you don't have to implement the update separately, you just post to /edit/$id instead of /update/$id ... this is a rough example, your slug checking (which I haven't touched upon) is not the correct way to do it, if it passes the validation the title is already filled since it's set to required so I guess you meant if (! empty(slug) ), but again in your else you are setting the slug directly from user input, so I would add it to the validation and make sure it's unique in the database except for the $id that's being edited currently.
Again, this is the result of copy & paste from your original code i might have missed something so give it a good read to make sure nothing is missing and include the validation errors in the data you are passing to the view.
I have managed to get the desired result using set_flashdata() as suggested by #Alex
In the controller I have:
public function update() {
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
$id = $this->input->post('id');
// Update slug (from title)
if (!empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$this->form_validation->run();
$this->session->set_flashdata('errors', validation_errors());
redirect('/posts/edit/' . $slug);
}
}
In the view:
<?php if ($this->session->flashdata('errors')) {
$errors = $this->session->flashdata('errors');
echo '<div class="error-group alert alert-warning alert-dismissible">' . "\n";
echo '<button type="button" class="close" data-dismiss="alert">×</button>' . "\n";
echo $errors;
echo '<p class="error-message">We have restored the post.</p>';
echo '</div>';
} ?>

Codeigniter - captcha for login is not working

I made a captcha login it is working so far but there is two problem and that problem is that first, when your username or password is wrong the page went to blank. Second, when both of the username,password and captcha are wrong the page went blank
but when your username and password are correct and the captcha is wrong it will call the echo'captcha is not correct';
function aksi_login(){
$data = array('username' => $this->input->post('username', TRUE),
'password' => md5($this->input->post('password', TRUE))
);
$this->load->model('m_model'); // load model_user
$hasil = $this->m_model->cek_user($data);
if ($hasil->num_rows() == 1 && $this->input->post('submit')){
$inputCaptcha = $this->input->post('captcha');
$sessCaptcha = $this->session->userdata('captchaCode');
if($inputCaptcha === $sessCaptcha){
foreach ($hasil->result() as $sess) {
$sess_data['logged_in'] = 'Sudah Login';
$sess_data['id_user'] = $sess->uid;
$sess_data['username'] = $sess->username;
$sess_data['level'] = $sess->level;
$this->session->set_userdata($sess_data);
}
if ($this->session->userdata('level')=='1') {
redirect('admin');
}
elseif ($this->session->userdata('level')=='2') {
redirect('guru');
}
elseif ($this->session->userdata('level')=='3') {
redirect('siswa');
}
else {
echo'username or password is wrong'
}
}
else{
echo "captcha code is not correct";
}
}
}
I think so far is because of the controller code and i have made some changes I tried putting another elseif like
elseif ($this->session->userdata('username')== FALSE && $this->session->userdata('password')==FALSE){
echo'username or password is wrong';
}
else {
echo'username or password is wrong';
}
but unfortunately is not working
Its better to check for captcha first in a separate condition then check for validation, so if you got everything right and your post values are all ok then you should do it like this:
if (this->captcha_validation($this->input->post('captcha')))
{
$this->form_validation->set_rules($this->rules);
if ($this->form_validation->run() === TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
// your magic
}
else
{
// array of validation errors
validation_errors = $this->form_validation->error_array();
}
}
else
{
// wrong captcha
$this->recaptcha();
}
Now you have isolated the two checks and made it way easier for recaptcha, but more importantly you don't need to make form validation if the captcha is wrong in the first place.
...
Not sure how your code works but in // your magic up there put your logic like this:
$this->load->model('m_model'); // load model_user
$hasil = $this->m_model->cek_user($data);
if ($hasil->num_rows() > 0)
{
foreach ($hasil->result() as $sess)
{
$sess_data['logged_in'] = 'Sudah Login';
$sess_data['id_user'] = $sess->uid;
$sess_data['username'] = $sess->username;
$sess_data['level'] = $sess->level;
$this->session->set_userdata($sess_data);
}
if ($this->session->userdata('level') == '1')
{
redirect('admin');
}
elseif ($this->session->userdata('level') == '2')
{
redirect('guru');
}
elseif ($this->session->userdata('level')=='3')
{
redirect('siswa');
}
}
My suggestion to to rewrite your controller and use Form Validation as it is also codeigniter standard library
Check the official documentation here
https://www.codeigniter.com/userguide3/libraries/form_validation.html
//your validation config should be something like this
public function login() {
$form_rules = [
[
'field' => 'username',
'label' => 'Username',
'rules' => 'required',
],
[
'field' => 'password',
'label' => 'Password',
'rules' => 'required',
],
[
'field' => 'captcha',
'label' => 'No HP',
'rules' => 'rules' => 'required|callback_check_captcha'
],
];
$this->form_validation->set_rules($this->form_rules);
if ($this->form_validation->run() == TRUE) {
//check username & password
//if you're sure that username is unique, you can directly get 1 data with ->row()
$check = $this->m_model->cek_user($data)->row();
if($check) {
switch($check->level) {
case '1' :
break;
case '2' :
......
......
}
} else {
//wrong username / password
}
} else {
//show login form with view
}
}
/*callback fro form validation*/
public function check_captcha($str) {
if(!empty($this->session->cap_word)) {
$expiration = time() - $this->config->item('captcha_expiration');
if($this->session->cap_time > $expiration) {
if($this->session->cap_word == $str) {
return TRUE;
} else {
$this->form_validation->set_message('check_captcha', 'Wrong captcha.');
return FALSE;
}
} else {
$this->form_validation->set_message('check_captcha', 'Session captcha expired.');
return FALSE;
}
} else {
$this->form_validation->set_message('check_captcha', 'KWrong captcha.');
return FALSE;
}
}

Add Variables to an array?

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');
}
}

CodeIgniter upload function, sometime not works

I have problem with codeigniter upload function.
The function works well, but sometimes didn't work and without any error info.
snippet in controller
...
function add_process() {
$data['title'] = anchor('event/','<b>EVENT</b>', array('class' => 'back'));
$data['subtitle'] = ' / Add Event';
$data['main_view'] = 'event/event_form';
$data['form_action'] = site_url('event/add_process');
$this->form_validation->set_rules('eventName', 'Event Name', 'required');
$this->form_validation->set_rules('eventDate', 'Event Date', 'required');
if (empty($_FILES['eventImage']['name'])){
$this->form_validation->set_rules('eventImage', 'Event Image', 'required');
}
if ($this->form_validation->run() == TRUE) {
$config['upload_path'] = './images/event/';
$config['allowed_types'] = 'jpg|jpeg|png';
//$config['max_width'] = '3000';
//$config['max_height'] = '3000';
$this->load->library('upload', $config);
$this->upload->do_upload('eventImage');
$eventImage = $this->upload->data();
$event = array( 'eventName' => $this->input->post('eventName'),
'eventDate' => date('Y-m-d', strtotime($this->input->post('eventDate'))),
'eventDescriptions' => $this->input->post('eventDescriptions'),
'eventImage' => 'images/event/'.$eventImage['file_name'],
'isActive' => $this->input->post('isActive')
);
$this->Event_model->add($event);
$this->session->set_flashdata('message', '1 record was successfully added!');
redirect('event/add');
} else {
$this->load->view('admin/admin_main', $data);
}
}
...
could you tell please, what am i missing here?
Replace this
$this->Event_model->add($event);
$this->session->set_flashdata('message', '1 record was successfully added!');
redirect('event/add');
to this
if ($this->Event_model->add($event)) {
$this->session->set_flashdata('message', '1 record was successfully added!');
redirect('event/add');
}

i couldn't insert data to database in codeigniter

i couldn't insert data to database and no error display. i try var_dump($this->mberita->get_berita()); but array(0){}. I am a newbie in Codeigniter and couldn't really figure out how to solve this.
modal
function get_berita()
{
$this->db->order_by('id_berita','asc');
$data = $this->db->get('berita_ukm');
return $data->result();
}
//untuk menambah berita
function insert_berita($data)
{
$this->db->insert('berita_ukm', $data);
}
controller
function index()
{
$this->data['berita'] = $this->mberita->get_berita();
$this->data['title'] ='UKM Taekwondo | berita';
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/berita/view_berita', $this->data, true);
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
function tambah_berita()
{
$this->form_validation->set_rules('id_berita', 'Id Berita', 'required|numeric');
$this->form_validation->set_rules('tanggal', 'Tanggal', 'required');
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/berita/tambah_berita');
}else{
$this->load->model('mberita');
$data = array(
'id_berita' => $this->input->post('id_berita'),
'tanggal' => $this->input->post('tanggal'),
'judul_berita' => $this->input->post('judul_berita'),
'content' => $this->input->post('content')
);
$this->mberita->insert_berita($data);
}
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/berita/tambah_berita', '', true);
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
Please help me what to do. Thank you.
Seems you may be missing the data you want to insert:
$this->mberita->insert_berita($data);
Your data is in the array data.But you don't pass it to the model.
So rewrite the code in controller as
$this->mberita->insert_berita($data);

Categories