CodeIgniter Forums
Handling non exsisting record mysql - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Handling non exsisting record mysql (/showthread.php?tid=67658)



Handling non exsisting record mysql - Marcel - 03-21-2017

Hi all

Ive done this code to handle a query that could give nothing if record dosnt exsist.

Code:
 function get_user_data()
   {
       $user_id = $this->auth->get_user_id();
       $default_array = array('user_id' => $user_id,
                            'test_a' => "please select an option",
                             'test_b' => "please select an option",
                              'test_c' => "please select an option",
                               'test_d' => "please select an option",
                                'test_e' => "please select an option",
                            );
                           
       $default= (object) $default_array;

       $this->db->select( '
         mytable.test_a ,
         mytable.test_b ,
         mytable.test_c,
         mytable.test_d,
         mytable.test_e');
       $this->db->from( 'mytable' );
       $this->db->where( 'user_id', $user_id );
       $this->db->trans_start();
       $this->db->trans_complete();
       $result = $this->db->get();
       if ( $result->num_rows() > 0 ):
           return $result->first_row();
       else:
           return $default;
       endif;
   }


Is this good practice ?.

this prevents me from doing a test in my view before displaying the data.

thanks for the advice