PHP-CRUD-2 : How to Insert data into database in php

In this post, you will be learning about how to insert data into database in php mysql, so, lets create a table named student to insert data in mysql using php as given in STEP 1

We are using Bootstrap v4 to design the user interface like forms and table.

So, Let's get started: (To insert data into database in php mysql).

Step 1: Create a database phpcrud and in that create a table named student : 

CREATE TABLE student (
    fname VARCHAR(30) NOT NULL,
    lname VARCHAR(30) NOT NULL,
    contact VARCHAR(50) NOT NULL,

Step 2: Create a file named insertdata.php and we will use bootstrap to design the form and store data through that html form, where code given below:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="">
    <title>Insert Data into Database in PHP</title>
    <div class="container">
        <div class="jumbotron">
            <div class="row">
                <div class="col-md-12">
                    <h2> PHP - CRUD : ADD Data </h2>
                    <form action="" method="post">
                        <div class="form-group">
                            <label for=""> First Name </label>
                            <input type="text" name="fname" class="form-control" placeholder="Enter First Name" required>
                        <div class="form-group">
                            <label for=""> Last Name </label>
                            <input type="text" name="lname" class="form-control" placeholder="Enter Last Name" required>
                        <div class="form-group">
                            <label for=""> Contact </label>
                            <input type="text" name="contact" class="form-control" placeholder="Enter Contact" required>

                        <button type="submit" name="insert" class="btn btn-primary"> Save Data </button>

                        <a href="index.php" class="btn btn-danger"> BACK </a>

Now, we have successfully created the HTML FORM using Bootstrap to insert data in STEP 2, so guys now lets write the code to insert data into database in php mysql in the same file just you created. (insertdata.php).

Paste the below given code at the TOP of the FILE named (insertdata.php)


$connection = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connection'phpcrud');

    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $contact = $_POST['contact'];

    $query = "INSERT INTO student(`fname`,`lname`,`contact`) VALUES ('$fname','$lname','$contact')";
    $query_run = mysqli_query($connection$query);

        echo '<script> alert("Data Saved"); </script>';
        echo '<script> alert("Data Not Saved"); </script>';


Thanks for reading...

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT