How to Insert data into database in php mysql

Insert data into database in php mysql

In this tutorial, you will learn how to insert data into database in php mysql, where we will create a form, database connection and finally the processing code to save your data in MySQL Database.

Let's create a table named as students in database as given below:

CREATE TABLE `students` (
    fullname varchar(55) NOT NULL,
    course varchar(55) NOT NULL,
    email varchar(55) NOT NULL,
    PRIMARY KEY (id)

So guys, Lets get started to insert data in database in php mysql:

Step 1: Create a file named dbconfig.php to give the database connection in php.

    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "your_database_name";

    // Create DB Connection
    $conn = mysqli_connect($host, $username, $password, $database);

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());

Step 2: Create a file named student.php to make a HTML FORM. Also we will be using bootstrap v5 to design the FORM.

<!DOCTYPE html>
<html lang="en">
    <title>Insert Data in PHP MySQL</title>
    <link href="" rel="stylesheet" />
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-header">
                        <h4>Insert data into database in PHP MySQL</h4>
                    <div class="card-body">

                        <form action="code.php" method="POST">

                            <div class="mb-3">
                                <label>Full Name</label>
                                <input type="text" name="fullname" class="form-control" required>
                            <div class="mb-3">
                                <input type="text" name="course" class="form-control" required>
                            <div class="mb-3">
                                <label>Email ID</label>
                                <input type="email" name="email" class="form-control" required>
                            <div class="mb-3">
                                <button type="submit" name="insert_buttton" class="btn btn-primary">Insert Data</button>



    <script src=""></script>
    <script src=""></script>

Step 3: Create a file named code.php to write the code to save data into database in php mysql.

    include_once 'dbconfig.php';

        $fullname = $_POST['fullname'];
        $course = $_POST['course'];
        $email = $_POST['email'];

        $query = "INSERT INTO students (fullname,course,email) VALUES ('$fullname','$course','$email')";
        $result = mysqli_query($conn, $query);
            echo "Data Inserted Successfully!";
            echo "Data Not Inserted!. Error: " . $sql . "" . mysqli_error($conn);

That's it. We successfully stored the Data.

Thanks for reading.