DEV Community

Brian
Brian

Posted on

Insert data in to MYSQL database using PHP

Requirements

  1. XAMPP/LAMPP Server

2.Editor( VS code/ Sublime text)

Step 1

Navigate to the htdocs folder and create folder named student, create an index.php in the student folder,

paste the code below

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Details Form</title> </head> <body> <h2>User Details Form</h2> <form action="process_form.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="course">Course:</label> <input type="text" id="course" name="course" required><br><br> <input type="submit" value="Submit"> </form> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

Create a new file process_form.php

<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Retrieve user input from the form $name = $_POST["name"]; $email = $_POST["email"]; $course = $_POST["course"]; // Database connection details $hostname = "localhost"; $username = "root"; $password = ""; $database = "tech_art"; // Create a database connection $conn = new mysqli($hostname, $username, $password, $database); // Check the connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Prepare and execute the SQL query to insert data into the database $sql = "INSERT INTO user_details (name, email, course) VALUES (?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("sss", $name, $email, $course); if ($stmt->execute()) { echo "<h2>Data saved successfully!</h2>"; } else { echo "<h2>Error: " . $stmt->error . "</h2>"; } // Close the statement and connection $stmt->close(); $conn->close(); } ?> 
Enter fullscreen mode Exit fullscreen mode

NB:Change the database details accordingly

Create the database and tables

Navigate to access the admin section that manages databases in Mysql

http://localhost/phpmyadmin/index.php

Create a database named tech_art,

Create a database

We'' use queries to create our table

Create a query

Paste the following query and run to create the table

 CREATE TABLE user_details ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, course VARCHAR(255) NOT NULL ); 
Enter fullscreen mode Exit fullscreen mode

This will create the table that will be used to store the details needed

Navigate to your browser and paste the following link

http://localhost/student/

Input the details and taraaa you have saved the details in the database!

Hope you had fun,incase of any question please reach out.

Top comments (0)