Back to Blog
Lesson 21 of the PHP: Modern PHP from the Ground Up course
PHPAugust 8, 20264 min read

Creating Data with CRUD: Mastering MySQL INSERT in PHP

Master the 'Create' step of CRUD by learning to write secure MySQL INSERT queries in PHP. Bind user input to your database and provide actionable feedback.

PHPMySQLCRUDDatabasesWeb DevelopmentBackend
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we learned the importance of executing prepared statements to interact with our database safely. Now that you have a secure connection established via PDO, it is time to implement the "Create" portion of CRUD (Create, Read, Update, Delete) to allow users to save information into your application.

The Anatomy of an INSERT Query

When a user submits a form, your application must translate that raw input into a structured row in your MySQL table. The INSERT INTO statement is the standard SQL command for this.

From a first principles perspective, the query follows a strict contract:

  1. Target Table: Specify the table name.
  2. Column List: Explicitly name the columns receiving data.
  3. Values: Provide the data corresponding to those columns.

Using raw string concatenation for these values is a security disaster—it leaves you wide open to SQL injection. Instead, we use placeholders (often ? or named parameters like :title) to decouple the SQL command from the user-provided data.

Worked Example: Persisting a Blog Post

Let’s extend our running project. Imagine we are building a "Post" feature. We have a posts table with title and content columns. Here is how we handle the form submission in our controller logic.

PHP
#6A9955">// Assuming $pdo is your established PDO connection instance
$title = $_POST['title'];
$content = $_POST['content'];

#6A9955">// 1. Prepare the SQL template
$sql = "INSERT INTO posts(title, content) VALUES(:title, :content)";
$stmt = $pdo->prepare($sql);

#6A9955">// 2. Bind parameters and execute
#6A9955">// Using an array in execute() is the cleanest way to bind inputs
$success = $stmt->execute([
    'title'   => $title,
    'content' => $content
]);

#6A9955">// 3. Provide feedback
if ($success) {
    echo "Post created successfully!";
} else {
    echo "Failed to save the post.";
}

Handling Insertion Feedback

In a real-world MVC application, you rarely want to simply echo success messages directly in the logic layer. Instead, you should provide feedback that the user can actually act upon.

  • Successful Inserts: Use a header redirect to send the user back to the list of items or the newly created item’s detail page, often with a "success" session flag.
  • Failed Inserts: If the database operation fails (e.g., a connection drop or constraint violation), catch the error. Wrap your execution in a try-catch block to ensure your app doesn't crash if the database is busy or the syntax is wrong.

Hands-on Exercise: Save a User Profile

  1. Create a simple HTML form with two inputs: username and email.
  2. In your store.php (or relevant controller), establish your PDO connection.
  3. Write an INSERT statement to add this data to a users table.
  4. After execution, use header('Location: /success.php') to redirect the user upon a successful save.
  5. Tip: Use lastInsertId() on your PDO object to retrieve the ID of the row you just created.

Common Pitfalls

  • Ignoring Constraints: If your database schema defines a column as NOT NULL, but your form doesn't provide it, the query will fail. Always validate your data using the techniques from our lesson on sanitization and validation before attempting the insert.
  • Assuming Success: Beginners often forget that execute() returns a boolean. Always check that boolean before telling the user everything went fine.
  • Mixing Logic and View: Avoid putting raw SQL inside your HTML templates. Keep this code in your controller or model layer to maintain a clean MVC architecture.

Frequently Asked Questions

Q: Do I need to manually close the connection after an insert? A: In modern PHP (using PDO), the connection is automatically closed when the script finishes execution. You generally don't need to close it manually.

Q: Can I insert multiple rows at once? A: Yes, you can extend the VALUES clause (e.g., VALUES (:a, :b), (:c, :d)), but for beginners, it is safer and more manageable to stick to one INSERT per request.

Q: What if the database table doesn't exist? A: Your prepare() or execute() call will throw a PDOException. If you haven't wrapped your code in a try-catch block, the user will see a raw error message, which is a security risk. Always use try-catch when performing database operations.

Recap

We've moved from simply reading input to actively storing it. By using INSERT queries with bound parameters, we ensure our data is stored securely and reliably. Remember that database operations are the heart of your application's state; treat them with care, validate input rigorously, and always handle potential errors gracefully.

Up next: We will explore how to modify existing data using UPDATE and DELETE queries to round out our full CRUD implementation.

Similar Posts