使用 php 动态向数据库添加多个注释的最佳方法

Best way to add multiple notes to a database with php dynamically

我目前有一个网站应该能够从用户输入中做笔记并将其保存到数据库中。我正在寻找有关实现此目标的最佳方法的一些指导。

该网站应该只显示最近添加的笔记,但所有其他笔记仍应保存(但隐藏)。不知道用户会输入多少次笔记。我最初的想法是每次用户输入笔记时动态地向数据库添加一列,但后来我最终为每个笔记都有一个新列 entry.Its 值得一提的是,笔记与文件名相关联,所以数据库中可能有很多行都有不同的注释。

dbforge 方法是我打算采用的方法,但它会反复尝试将 'notes' 添加到数据库(一次操作后就已经存在)。

$fields = array(
            ('notes') => array('type' => 'TEXT','constraints' =>'255')
        );
        $this->dbforge->add_column('mytable', $fields);

有人知道更好的方法吗?我正在使用 php 和 codeigniter 框架。 非常感谢所有帮助!

我会有一个注释 table,它存储用户 ID、注释和添加日期。

在您看来,您的表单将在您的控制器中指向这个:

public function addNote($user_id)
{
    $this->form_validation->set_rules('note', 'Note', 'required');

    if ($this->form_validation->run() == true) {

        $array = array (
            'user_id'   => $user_id,
            'note'      => $this->input->post('note')
        );

        $this->your_model->addRecord('notes', $array);
    }
}

模型中的addRecord()函数看起来像:

public function addRecord($table, $array)
{
    $this->db   ->insert($table, $array);

    return $this->db->insert_id();
}

然后您可以执行这样的查询并将结果传回您的视图:

public function getLatestNoteByUser($user_id) 
{
    $this->db->select('id, note')
             ->from('notes')
             ->where('note_added_by', $user_id)
             ->order_by('date_added', desc)
             ->limit(1);

    return $this->db->get()->row();
}

这将 return 仅指定用户添加的最后一条注释。您可以将限制设置为您想要的任何值,并且 return row_array() 而不是 row()。您甚至可以在函数参数中传递 $limit,并使用 ->limit($limit).