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


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

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

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

dbforge 方法是我要做的方法,但它会反复尝试向数据库添加"注释"(一次后已经存在)。

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

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

我会有一个存储用户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();
}

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