【问题标题】:Is there a way to check if data exists then insert the data? CodeIgniter有没有办法检查数据是否存在然后插入数据?代码点火器
【发布时间】:2020-03-22 16:00:03
【问题描述】:

我需要知道当数据存在于表中时如何插入数据。另一方面,如果数据确实存在,则不会插入。有没有办法做到这一点?

我的观点

<?php echo form_open('students/find_class   ') ?>
    <input type="hidden" value="1" name="studId" />
        <div class="form-group">
            <h5>Class Code:</h5>
            <small><li>Only teachers shall give you code</li></small><br>
            <input type="text" class="form-control col-md-6" placeholder="Enter class code to join" name="code" required />
                            
       </div>
        <hr>
        <button type="submit" class="btn btn-info btn-md">Join Class</button>
</form>

我的控制器将通过模型连接

public function find_class(){
    $this->student_model->find_class();

    redirect('students/home');

}

最后,我的模型

public function find_class(){

    $data = array(
        'student_id' => $this->user_id,
        'code' => $this->input->post('code')
    );

    return $this->db->insert('classes', $data);
}

【问题讨论】:

  • 请在插入逻辑之前添加一个PHP逻辑来检查数据是否存在。没有别的办法!

标签: php mysql codeigniter codeigniter-3


【解决方案1】:

只有这个 sql 代码:

INSERT INTO table (value1, value2, value3)
SELECT * FROM (SELECT value1_content, value2_content, value3_content) AS tmp
WHERE NOT EXISTS (
    SELECT value1 FROM table WHERE value1 = value1_content
) LIMIT 1;

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
相关资源
最近更新 更多