0

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.

4

1 回答 1

1

我发送到服务器的 jQuery 对象中的名称是否必须与数据库中的字段名称相同才能使用 codeigniter $this->db->insert('mytable', $data); 方法?

不,您在$data数组中指定字段名称:

$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

如果不明确指定要在哪个 id 处插入它们,我将如何插入值标题和消息,以便将这个数据集添加到数据库的第一个空白处。

创建数据库表时,应将该id字段指示为主键/自增。id这将根据表中的行数自动生成值。这是标准过程,如果您从其他地方获得数据库或遵循教程,则可能是如何设置数据库的。

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

于 2013-01-24T21:11:48.253 回答