Database : Insert (CRUD)

  • insert_into : The query method directive is the top level sql setter method for inserting data into database fields. It defines sql insert queries that can be executed later.

    Example 1 : sql setter with chained controllers
      $db->insert_into('users')
    
         ->columns(['id', 'username'])
    
         ->values(['1', 'Felix']);
                

    The method above is used to set simple sql queries. Methods columns() and values() can only be chained once on the insert_into() operator in the predefined order.

    Method 2 (Binded Parameters)
    In the example below, columns and values are defined as an array of key(field) and value pairs. The username represents the database column name and Felix as its respective value. Several keys and their respective values can be supplied.
    Example 2 (Binded Parameters)
      $db->insert_into('users', ['username' => 'Felix']);
                


    Recommend: Method 2 above works similarly as method 1. It is concise and easier to read which makes it the best choice for setting up insert queries
    Footnote: It is worth noting that query() method can also be used for setting up sql insert queries and may be used to handle multiple insertions

  • insert : This method is used to execute database queries relating to insertions.

    Example 1 : Data insertion
      $db->query('insert into users')
         ->columns(['id', 'username'])
         ->values([1, 'Felix'])
         ->insert();
                


    Example 2 : Data insertion
      $db->insert_into('users')
         ->columns(['id', 'username'])
         ->values([1, 'Felix'])
         ->insert();
                


    Example 3 : Data insertion
      $db->insert_into('users',['id' => 1, 'username' => 'Felix'])
         ->insert();
                


    Example 4 : Data insertion
      $db->query('insert into users columns(id, username) values(?, ?)', [ 1, 'Felix'])
         ->insert();
                


    Example 5 : Multiple Data insertion
      $db->insert_into('users', [ 'id' => [1, 2, 3], 'username'=>['Felix','Richard','Brymo']])
         ->insert();
                


  • Footnote:
    Method 3 above seems to be the easiest, but when handling complex queries, it is preferred to use the query approach in Example 4 above. Also, when inserting multiple data, we can use the approach in method 5 above where data will be splitted into different rows relative to their field (or column) names. It is important to ensure that the data supplied for columns in method 5 above have equal number of array values to prevent value misplacement or errors.