insert()

public function insert(array $data, string $table): int

Description

Inserts a single record into a specified database table and returns the ID of the newly inserted record. This method validates table existence, constructs a parameterized INSERT query from an associative array, and uses prepared statements to prevent SQL injection. Returns the auto-generated ID from the last insert operation.

Parameters

Parameter Type Description Default Required
data array Associative array where keys are column names and values are the data to insert. - Yes
table string The name of the database table to insert into. - Yes

Return Value

Type Description
int The ID of the newly inserted record. Always returns an integer (cast from lastInsertId()).

Exceptions

  • RuntimeException - If the specified table does not exist in the database.
  • PDOException - If the database operation fails (e.g., constraint violation, connection error).

Example #1

The code sample below demonstrates how to insert a new user record into the 'users' table.

PHP
$user_data = [
    'username' => 'john_doe',
    'email' => '[email protected]',
    'password' => password_hash('secret123', PASSWORD_DEFAULT),
    'created_at' => date('Y-m-d H:i:s')
];

$new_user_id = $this->db->insert($user_data, 'users');
echo "New user created with ID: " . $new_user_id;

Example #2

The code sample below demonstrates how to insert a product record into the 'products' table.

PHP
$product_data = [
    'name' => 'Wireless Headphones',
    'description' => 'Noise-cancelling over-ear headphones',
    'price' => 199.99,
    'stock_quantity' => 50,
    'category_id' => 3
];

$product_id = $this->db->insert($product_data, 'products');
echo "Product inserted with ID: " . $product_id;

Example #3

The code sample below demonstrates how to insert a record with different data types (string, integer, float, and null).

PHP
$order_data = [
    'customer_name' => 'Jane Smith',           // string
    'customer_id' => 123,                      // integer
    'total_amount' => 149.50,                  // float
    'notes' => null,                          // null value
    'order_date' => date('Y-m-d')             // date string
];

$order_id = $this->db->insert($order_data, 'orders');
echo "Order #" . $order_id . " has been created.";

Important Notes

  • Both parameters ($data and $table) are required.
  • The method validates that the table exists before executing the INSERT query.
  • Column names from the $data array are automatically used to construct the INSERT statement.
  • Uses prepared statements with parameter binding for security against SQL injection.
  • Returns the last insert ID as an integer (cast from string).
  • Requires the table to have an auto-increment column to return a meaningful ID.
  • Data types are automatically handled (strings, integers, floats, booleans, null values).
  • If debug mode is enabled, the generated SQL query will be displayed before execution.