Home > Backend Development > PHP Tutorial > Detailed introduction to the method of rewriting insert using Codeigniter

Detailed introduction to the method of rewriting insert using Codeigniter

黄舟
Release: 2023-03-06 21:20:02
Original
1170 people have browsed it

The following editor will bring you an article on how to use Codeigniter to rewrite insert (recommended). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look.

There is a unique index key value when inserting data using the Codeiginter framework. Solution

Storing the data When, there will be some unique index fields that already have values, and it will fail when inserting data. Our usual solution is to first query whether the value exists, and if it exists, it will be updated as soon as new update, if it does not exist, insert it. The following is a rewrite of the insert method in Codeigniter model, which greatly simplifies the steps!

/**
 * 插入单条记录(Insert)
 *
 * @param array $params 插入字段及值数组
 * @param string $table 插入表名,未指定的场景插入主表
 * @param array $columns 插入表中所属字段名数组,若指定则按此进行过滤
 * @param array $updateColumns 若唯一键冲突时需要更新的列数组
 * @return mixed FALSE:没有插入的字段 int:插入记录id
 *
 * @throws \C_DB_Exception
 */
public function insert($params, $table = NULL, $columns = array(), $updateColumns = array())
{
  // 如果未指定表名,则认为对本Model层的主表进行操作
  if (empty($table)) {
    $table = $this->table;
    $columns = $this->columns;
  }
  // 过滤掉不属于该表中的字段
  if ( ! empty($columns)) {
    foreach ($params as $column => $val) {
      if (in_array($column, $columns)) {
        $row[$column] = $val;
      }
    }
  }
  // 不过滤
  else {
    $row = $params;
  }
  // 没有插入字段,直接返回
  if ( ! isset($row)) {
    return FALSE;
  }
  // 保证创建时间、更新时间必须设置
  if ( ! isset($row['create_at']) && in_array('create_at', $columns)) {
    $this->load->helper('common_function');
    $datetime = get_datetime();
    $row['create_at'] = $datetime;
    $row['update_at'] = $datetime;
  }
  // 封装SQL文,过滤不安全因素
  $sql = $this->db->insert_string($table, $row);
  // 若唯一键冲突时需要更新的列数组,则再次封装SQL文
  if ( ! empty($updateColumns)) {
    $updateValues = '';
    foreach ($updateColumns as $updateColumn) {
      if (isset($updateValues[0])) {
        $updateValues .= ',';
      }
      $updateValues .= $updateColumn . '=VALUES(' . $updateColumn . ')';
    }
    $sql = $sql . ' ON DUPLICATE KEY UPDATE ' . $updateValues;
  }
  // SQL执行
  $query = $this->db->query($sql);
  // SQL执行失败,抛出异常
  if (FALSE === $query) {
    $code = $this->db->_error_number();
    $msg = $this->db->_error_message();
    C_log::Error($code . ':' . $msg, $this->user_id, $sql, self::STATUS_DB_LOG);
    throw new C_DB_Exception('', C_DB_Exception::DB_ERR_CODE);
  }
  // SQL文写入DB日志
  if (LOG_UPDATE_SQL) {
    C_log::Info('', $this->user_id, $sql, self::STATUS_DB_LOG);
  }
  // 取得插入ID返回
  $id = $this->db->insert_id();
  return $id;
}
Copy after login

If you write SQL directly, there is another statement

Syntax: INSERT INTO table VALUES () ON DUPLICATE KEY UPDATE row='$row'

For example:

INSERT INTO it_teacher (uid,name,qq,create_at) 
VALUES ('$userid','$name','$qq',NOW()) ON DUPLICATE KEY UPDATE name='$name',qq='$qq',phone='$phone'";
Copy after login

The above is the detailed content of Detailed introduction to the method of rewriting insert using Codeigniter. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template