Welcome Guest, Not a member yet? Register   Sign In
If user ID exists in database, UPDATE. Otherwise, INSERT (HELP)
#1

[eluser]Barwick[/eluser]
So as the title explains, I'm creating a subscription function that's connected to a "subscriptions" database. On the form, a logged in user is required to select a subscription. 3 different options. In the form, I have two hidden fields, one for user ID and the other for email address. Both pulled from the session data.

In my controller and model below, I want to (1) check to make sure the user hasn't already set-up a subscription (verified by user ID). If they haven't, it's added on form submit. If the query comes back true that a subscription was created previously using the user ID, then I'd like to update the table row.

But all my code wants to do is INSERT even if there's already a record in the database. What am I doing wrong? Duplication error will occur...

Controller (part of it):
Code:
public function update()
    {
        $userid = $this->session->userdata('user_id');  
        
        $this -> db -> where('id');
        $query = $this -> db -> get('subscriptions');
        
        if($query -> num_rows() == $userid) // Check to see if user id exists
        {
            // if subscription record found, update:
            $this -> subscribe_model -> update_subscription();
            redirect('dashboard');            
        }
        else
        {
            // if no records found, add:
            $this -> subscribe_model -> add_subscription();
            redirect('dashboard');  
        }
    }

Model:
Code:
class Subscribe_model extends CI_Model {
    
    public function __construct() {
        parent::__construct();
    }
    
    // Add Subscription to database
    public function add_subscription()
    {
        $data = array(
            'id' => $this -> input -> post('userID'),
            'email' => $this -> input -> post('userEmail'),
            'subscription' => $this -> input -> post('package')
        );
        $this -> db -> insert('subscriptions', $data);
    }
    
    // Update Subscription to database
    public function update_subscription()
    {
        $data = array(
            'id' => $this -> input -> post('userID'),
            'email' => $this -> input -> post('userEmail'),
            'subscription' => $this -> input -> post('package')
        );

        $this->db->where('id', $id);
        $this->db->update('subscriptions', $data);
    }
    

}


Messages In This Thread
If user ID exists in database, UPDATE. Otherwise, INSERT (HELP) - by El Forum - 11-05-2012, 05:33 PM



Theme © iAndrew 2016 - Forum software by © MyBB