Back to course

CRUD Operations with PDO: Inserting Data

PHP: The Complete 0 to Hero Bootcamp

46. CRUD Operations with PDO: Inserting Data

CRUD stands for Create, Read, Update, Delete. 'Create' involves inserting new records into a database table using the SQL INSERT command.

Prepared Statements for Insertion

Instead of putting user data directly into the SQL string, we use placeholders (? or named parameters :param). This separates the SQL command from the data, which prevents SQL Injection.

Steps:

  1. Prepare: Define the SQL query with placeholders.
  2. Bind: Associate actual values with the placeholders.
  3. Execute: Run the prepared statement.

php

prepare($sql); // $stmt is the statement handler // 2. Bind parameters to prevent SQL injection $stmt->bindParam(':username', $new_username); $stmt->bindParam(':email', $new_email); // 3. Execute the statement $stmt->execute(); echo "New user inserted successfully."; // Getting the ID of the last inserted record $last_id = $pdo->lastInsertId(); echo "
New user ID: $last_id"; ?>

Named Parameters vs. Question Marks: Named parameters (:param) are generally easier to read and maintain, especially with complex queries.