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.

Example #2

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

Example #3

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

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.