TheBaj
TheBaj

Reputation: 1141

Inserting into Database using Codeigniter

I am trying to enter some data which I post to the server via jquery.post into a database.

note = { // note object that will be sent to the server
    title: $('input.xlarge').val(); ,
    message: $('textarea.xlarge').val(); ,
    }

$.post(link + "cart/addtodb", note,
            function(data){

            if(data == 'true'){
                alert('Your note has been saved');
            }else{
                alert("Something went wrong");
            }   

         });

Here is my codeigniter php code for the controller to which the data is being sent:

public function addtodb()
    {
     $note = $this->input->post('note');
     $this->postit_model->addnote($note);
     echo 'true';  //send true response to client after note has been added to db
    }

Now I have a database table called posts with the fields: id, title, message. I want to insert the passed set of data into the database.

Questions: -Do the names in the jQuery object that i send to the server have to be the same as the field names in the database to be able to use the codeigniter $this->db->insert('mytable', $data); method?

-How would i go about inserting the values title and message without explicitly specifying at which id i want to insert them so that this dataset will just be added to the database in the first empty spot.

Upvotes: 0

Views: 1543

Answers (1)

stormdrain
stormdrain

Reputation: 7895

Do the names in the jQuery object that i send to the server have to be the same as the field names in the database to be able to use the codeigniter $this->db->insert('mytable', $data); method?

No. You indicate the field names in the $data array:

$data = array(
    'field_name' => 'field value',
    'other_field' => 'other field value'
);
$this->db->insert('my_table', $data);

http://ellislab.com/codeigniter/user-guide/database/active_record.html#insert

How would i go about inserting the values title and message without explicitly specifying at which id i want to insert them so that this dataset will just be added to the database in the first empty spot.

When the database table is created, you should indicate the id field as primary key/auto increment. This will automatically generate the id value based on the number of rows in the table. This is standard procedure and is likely how the database is set up if you got it from somewhere else or were following a tutorial.

http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Upvotes: 1

Related Questions