Insert Data using PHP & MySQL Database
Introduction
Inserting data into a MySQL database is a fundamental operation in web development. This guide will teach you how to perform this task using core PHP. By following this tutorial, you will learn efficient and secure methods to handle user input and manage database operations while adhering to Google SEO best practices.
Prerequisites
- Basic knowledge of PHP and MySQL.
- A MySQL database with a table ready to store data.
- A web server (e.g., XAMPP, WAMP, or a live server) to execute PHP scripts.
Steps to Insert Data in MySQL
1. Create a Database and Table
Run the following SQL commands to create a database and a table for storing data:
CREATE DATABASE demo_db; USE demo_db; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, age INT NOT NULL );
2. Establish a Database Connection in PHP
<?php // Database connection settings $host = 'localhost'; $user = 'root'; $password = ''; // Use your database password $database = 'demo_db'; // Create connection $conn = new mysqli($host, $user, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
3. Create an HTML Form for User Input
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Insert User Data</title> <meta name="description" content="Learn how to insert data into MySQL using PHP with this comprehensive tutorial."> </head> <body> <h2>Add New User</h2> <form action="insert.php" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br><br> <label for="email">Email:</label> <input type="email" id="email" name="email" required><br><br> <label for="age">Age:</label> <input type="number" id="age" name="age" required><br><br> <button type="submit">Submit</button> </form> </body> </html>
4. Handle the Insert Operation in PHP
Create a file named insert.php
to process the form submission and insert the data into the database:
<?php // Include the database connection file include 'db_connection.php'; // Get data from the form $name = $_POST['name']; $email = $_POST['email']; age = $_POST['age']; // Prepare the SQL query to insert data $sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("ssi", $name, $email, $age); // Execute the query if ($stmt->execute()) { echo "Record inserted successfully."; } else { echo "Error inserting record: " . $conn->error; } // Close the connection $stmt->close(); $conn->close(); ?>
0 Replies to “Insert Data Using PHP & Mysql Database”
Leave a Reply
Your email address will not be published.