Как я могу сохранить значение переменной, если проверка не проходит в codeigniter - PullRequest
0 голосов
/ 18 декабря 2018

Я хочу проверить форму, чтобы убедиться, что пользователь ввел что-то в поле описания в этой ситуации. Проверка правильности формы.

Но,

Здесь я передаю значение функция 2 путем извлечения значений из функция 1

Когда функция 2 загружает в первый раз данные и отображает значения (ОК)

Но когда функция 2 повторно отправляет данные для проверки и передачи, эти действительные получают empoty и выдают ошибку Message: Undefined variable: query (ОШИБКА)

Я не знаю, как это сделать, хе-хе.Я просто новичок в программировании на PHP.

Вот что у меня есть:

функция 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);
    }   
}

функция 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);
        }     
    }   

}

Ответы [ 3 ]

0 голосов
/ 19 декабря 2018

На самом деле у вас есть переменная $ data, вставленная в другую часть, поэтому эту ошибку нужно определить перед циклом.

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

}
0 голосов
/ 20 декабря 2018

Попробуйте использовать этот код:

Сначала добавьте библиотеку форм в config / autoload.php

$autoload['libraries'] = array('database','form_validation');

html Code

Это представление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);
        }
    }

Попробуйте этот код. Вы можете сохранить значение переменной, если проверка не удалась вуспешно кодируйте.

0 голосов
/ 19 декабря 2018

Если вы хотите использовать переменную $data для условия false, вы можете переместить ее за пределы блока проверки:

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

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...