PHP inserting values to database

      No Comments on PHP inserting values to database

PHP inserting values to database:

To insert data in database, we need a form. HTML forms can get data input from user which can be stored in database.

Forms can be submitted by two methods:

  • GET: data sent using GET is visible in the url
  • POST: generally used to send confidential data to the database.

The form tag is specified as show below:

<form method="GET/POST" action="request-handler.php">

Creating a form

  1. Form is enclosed in <form> </form> tags.
  2. Specify the method attribute as GET or POST depending on the data being sent to the php script
  3. Set the action attribute with the URL of the php script eg:request-handler.php
  4. NOTE: Each input/select/textarea field in the form should contain name attribute. Without name attribute the value submitted will not be sent to the script.
  5. A sample form

    <form method="POST" action="request-handler.php">
      <input type="email" name="email" placeholder="Enter Email" required/>
      <input type="password" name="password" placeholder="Password" required/>
      <input type="submit" value="login"/>

    Demo databse


    PHP inserting values to database


    PHP inserting values to database

    PHP inserting values to database- request-handler.php

      if(isset($_POST['submit'])) //avoid error:undefined index
          $email=$_POST['email']; //getting values from the form
      // establishing a database connection
      define("HOST", "localhost");     // The host you want to connect to.
      define("USER", "user_db");    // The database username. 
      define("PASSWORD", "123$%bb^7aqq!2");    // The database password. 
      define("DATABASE", "sample_db");    // The database name.
      $connection = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
      // Check connection
      if (mysqli_connect_errno())
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
      // checking for empty variables
      if($email="" ||$password="")
        echo "Please enter a valid value to each input";
        //building a query
        $sql="INSERT INTO `user`(`email`,`password`) VALUES ('$email','$password')";
        //running query
        //success message
            echo "Logined in";


    Inserting values through form:

    PHP inserting values to database

    Updation in table:

    PHP inserting values to database

Leave a Reply

Your email address will not be published. Required fields are marked *