Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Insert data into database from form in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 432
    Comment on it

    Below is a form which contain id field, name field, phone number filed, gender radio button and we are sending these data  by using post method.

    
    <form name="user_registration" method="post" >
       Name: <input type="text" name="Name">
     
       <br><br>
    
        phone: <input type="text" name="phone">
        
        <br><br>
       
        E-mail: <input type="text" name="email">
      
        <br><br>
    
       Gender:
       <input type="radio" required name="gender" value="female">Female
       <input type="radio" required name="gender" value="male">Male
       
       <br><br>
       <input type="submit" name="submit" value="Submit">
    </form>

    For inserting data to database from form in php, first we have to create a connection from database by using following code.

    <?php
    $servername = "localhost";
    $username = "root"; 
    $password = "pass";
    $database = "demo";  //this will contain name of a database
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
      echo "Connected successfully";
    
    	
    ?> 

    Below code will insert data from above form to database.

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $id = $_POST['id']; // it stores id which we are providing in id field
    $name = $_POST['Name']; // it stores name which we are providing in name field
    $Phone = $_POST['phone']; // it stores phone number which we are providing in phone field
    $email=$_POST['email']; // it stores email address which we are providing in email field
    $Gender= $_POST['gender']; // it stores gender information which we are providing
    
    
    
    // sgl query for inserting record
    
    $sql = "INSERT INTO user(Name,email,phone,gender) VALUES ('".$name."','".$email."',".$Phone.",'".$Gender."')";
    
    
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: