In this tutorial, we will learn how to insert records into a MySQL database using PHP. We will use the mysqli
extension to connect to the database and execute an insert query. Let’s get started!
Step 1: Create a MySQL Database and Table
Before we can insert records, we need a database and a table. Here’s an example SQL statement to create a database and a table:
CREATE DATABASE my_database;
USE my_database;
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
Step 2: Connect to the MySQL Database
Next, we need to connect to the MySQL database using PHP:
$servername = "localhost";
$username = "root"; // Replace with your database username
$password = ""; // Replace with your database password
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Step 3: Insert a Record
Now that we have a connection to the database, we can insert a record. We will prepare an SQL statement and execute it:
$name = "John Doe";
$email = "john.doe@example.com";
// Prepare and bind
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
// Close the statement
$stmt->close();
Step 4: Close the Connection
After inserting the record, don’t forget to close the database connection:
$conn->close();
Final Thoughts
In this tutorial, you learned how to insert a record into a MySQL database using PHP and the mysqli
extension. By preparing and executing SQL statements, you can easily manage your database records. This knowledge is fundamental for building dynamic web applications that require database interaction!