← Back to Chapters

PHP MySQL CRUD – Create Data

? PHP MySQL CRUD – Create Data

? Quick Overview

The Create operation is the first step in CRUD (Create, Read, Update, Delete). It is used to insert new records into a MySQL database using PHP through SQL INSERT INTO queries.

? Key Concepts

  • CRUD operations form the foundation of database-driven applications
  • PHP communicates with MySQL using MySQLi or PDO
  • The INSERT INTO statement is used to add new records

? Syntax / Theory

The basic SQL syntax to insert data into a table:

INSERT INTO table_name (columns) VALUES (values)

? Code Example

? View Code Example
// PHP script to insert data into MySQL using MySQLi
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to insert data
$sql = "INSERT INTO users (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com')";

// Execute query and check result
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $conn->error;
}

// Close connection
$conn->close();
?>

? Live Output / Explanation

Output

If the query executes successfully, the message New record created successfully will be displayed. Otherwise, an error message will appear.

? Interactive Example

You can enhance this logic by connecting it to an HTML form where users submit their data, which is then inserted into the database dynamically.

? Use Cases

  • User registration systems
  • Contact form submissions
  • Admin panels for adding records
  • Online surveys and feedback forms

✅ Tips & Best Practices

  • Use prepared statements to prevent SQL injection
  • Always validate and sanitize user input
  • Hash sensitive data like passwords before storing

? Try It Yourself

  • Add new columns like age or phone number
  • Rewrite the example using PDO
  • Connect the script to an HTML form
  • Implement server-side input validation