Trongate Docs
switch to dark modeswitch to dark mode
»
»
The 'Insert' Method

The 'Insert' Method

The Insert Method inserts a row of data into a database table. With this method, rows of new data are represented by a PHP array. This method accepts the following parameters:

  • $data (required) - an array of key, value pairs representing the table row that is to be inserted.
  • $target_table (optional) - the name of the database table where the new row is to be inserted. By default, the Model will assume the target table to be equal to the value on the first URL segment.

What Gets Returned?

WHEN A NEW ROW IS INSERTED

If the Method results in a new table row being inserted then the 'id' of the newly inserted record will be returned.

Example 1

The syntax below shows the simplest Insert example possible.  In this example, we create an array of data that represents a new table row.  Then, we invoke 'Insert' and add a new row onto a database table, using the array that we have created.

$data['first_name'] = 'Eric'; 
$data['last_name'] = 'Clapton';
$data['trongate_user_id'] = 91;
$this->model->insert($data);

The code above will produce the following SQL query:

INSERT INTO tablename (first_name, last_name, trongate_user_id) VALUES ('Eric', 'Clapton', 91)

Just To Let You Know
In a working example, 'tablename' would be replaced with the first segment from the URL.

Below is an example of a Members.php controller file that contains a test() method.  Here we're invoking a basic 'Insert' command and then immediately displaying the results using Trongate's json() method:

<?php
class Members extends Trongate {

    function test() {
        $data['first_name'] = 'Eric';
        $data['last_name'] = 'Clapton';
        $data['trongate_user_id'] = 91;
        $this->model->insert($data);
    }

Below shows an example of the kind of output that we can expect to see from the above method, when Debug Mode is switched on:

screenshot

Example 2

Below is a more advanced example.  In this example, we have an alternative way of creating a data array and we also fetch then display the 'id' of the newly inserted table row:

function test() { 
    $data = array('first_name' => 'Jimi',
                  'last_name' => 'Hendrix',
                  'trongate_user_id' => 92);

    $id = $this->model->insert($data, 'members');
    echo 'The new record ID is: '.$id;
}

The code above would produce the following SQL query:

INSERT INTO members (first_name, last_name, trongate_user_id) VALUES ('Jimi', 'Hendrix', 92)



HELP & SUPPORT

If you have a question or a comment relating to anything you've see here, please goto the Help Bar.

 
×