Welcome Guest, Not a member yet? Register   Sign In
The worst code I've written :(
#1

[eluser]iainco[/eluser]
Problem: Users select sports using HTML chechboxes and their selections are saved in a database. What is the best way of displaying checkboxes already selected for those which have been saved as selected?

Model
Code:
function fetchSports()
    {
        $sports = array();
        $sport = $this->db->get('sport');
        
        if($sport->num_rows() > 0)
        {
            $sports = $sport->result();
        }
        
        return $sports;
    }
    
    function fetchUserSports()
    {
        $count = 0;
        $userSports = array();
        $user_sport = $this->db->query('SELECT `sportID` FROM `user_sport` WHERE `userID` = ' . $this->db->escape($this->session->userdata('ID')));
        
        foreach($user_sport->result() as $row)
        {
            $userSports[$count] = $row->sportID;
            $count++;
        }
        
        return $userSports;
    }

View
Code:
<? foreach($sports as $sport): ?>
&lt;?=$sport->title?&gt; &lt;input type="checkbox" name="sports[]" value="&lt;?=$sport-&gt;ID?&gt;" &lt;?=(in_array($sport->ID, $userSports)) ? 'CHECKED': '';?&gt; /><br />
&lt;? endforeach; ?&gt;

Controller
Code:
function index()
    {
        $this->load->view('Profile_View', array('sports' => $this->Profile_Model->fetchSports(), 'userSports' => $this->Profile_Model->fetchUserSports()));
    }

That's my first try, but it is terribly messy... I think my cold is preventing me from seeing a much more elegant solution!

*cries*


Messages In This Thread
The worst code I've written :( - by El Forum - 08-13-2008, 09:47 AM
The worst code I've written :( - by El Forum - 08-13-2008, 01:16 PM
The worst code I've written :( - by El Forum - 08-13-2008, 01:26 PM
The worst code I've written :( - by El Forum - 08-14-2008, 05:48 PM



Theme © iAndrew 2016 - Forum software by © MyBB