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.
The basic SQL syntax to insert data into a table:
// 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();
?>
If the query executes successfully, the message New record created successfully will be displayed. Otherwise, an error message will appear.
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.