Welcome Guest, Not a member yet? Register   Sign In
Can I convert empty strings to NULL with a Codeigniter validation rule?
#8

(02-28-2019, 12:45 PM)b126 Wrote: I did it and it’s working fine, with strings, and also with numeric values. 
Here is my /application/core/MY_Input.php

PHP Code:
class MY_Input extends CI_Input {
 
   public function post($index NULL$xss_clean NULL)
 
   {
 
       $value$this->_fetch_from_array($_POST$index$xss_clean);
 
       return $value === '' null $value;
 
       //return isset($value) ? $value : (isset($default_fail) ? $default_fail : NULL);
 
   }


One thing to be aware of is your code introduces a bug when you ask CI_Input::post() to return the entire $_POST array. i.e.
PHP Code:
$data $this->input->post(); 

That might not be something you ever do, but future code maintenance or changes might run up against this. It's an easy thing to forget and a hard thing to point out to someone else coming to the project.

I think you have to either override _fetch_from_array() - which is not as trivial as what you've done - or,  you could do the following

PHP Code:
public function post($index NULL$xss_clean NULL)
{
 
   $data $this->_fetch_from_array($_POST$index$xss_clean);
 
   if(is_array($data))
 
   {
 
       $output = array();
 
       foreach($data as $key => $value)
 
       {
 
           $output[$key] = $value === '' NULL $value;
 
       }
 
       return $output;
 
   }
 
   return $data === '' null $data;


Have you considered that you might want to trim the input in case somebody enters a string with empty spaces?
Reply


Messages In This Thread
RE: Can I convert empty strings to NULL with a Codeigniter validation rule? - by dave friend - 02-28-2019, 01:39 PM



Theme © iAndrew 2016 - Forum software by © MyBB