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:
- Prepare: Define the SQL query with placeholders.
- Bind: Associate actual values with the placeholders.
- 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.