【问题标题】:Inserting into Database using Codeigniter使用 Codeigniter 插入数据库
【发布时间】:2013-01-24 20:44:40
【问题描述】:

我正在尝试将我通过 jquery.post 发布到服务器的一些数据输入到数据库中。

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");
            }   

         });

这是我的 codeigniter php 代码,用于将数据发送到的控制器:

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
    }

现在我有一个名为 posts 的数据库表,其中包含以下字段:id, title, message. 我想将传递的数据集插入到数据库中。

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

-我将如何插入值 title 和 message 而没有明确指定我想在哪个 id 插入它们,这样这个数据集就会被添加到数据库的第一个空点。

【问题讨论】:

    标签: jquery database codeigniter object model


    【解决方案1】:

    在我发送到的 jQuery 对象中执行名称 服务器必须与数据库中的字段名称相同 能够使用代码点火器 $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

    【讨论】:

    • 在 $data 数组中,table_name 和 other_table 是指字段,在这种情况下:标题和消息对吗?
    猜你喜欢
    • 2013-04-04
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多