The INSERT statement is used to add new records to a database table by specifying column names and values.
$sql = "INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)";
Using parameterized queries can effectively prevent SQL injection attacks. Bind parameters to placeholders instead of directly concatenating user input into the query string.
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);
Use the INSERT ... SELECT statement to insert data in bulk from another table.
$sql = "INSERT INTO table1 (column1, column2) SELECT column1, column2 FROM table2";
Use the LAST_INSERT_ID() function or $conn->insert_id to get the automatically generated ID for further operations.
$id = $conn->insert_id;
Transactions ensure that a group of database operations either all succeed or all fail. Common functions include begin_transaction(), commit(), and rollback().
Use the mysqli_error() function to capture and handle errors that occur during database operations.
if ($stmt->execute()) {
// Execution successful
} else {
echo "Error: " . $stmt->error;
}