Friday, 8 September 2017

How to insert form data into a MySQL database using PHP



HOW TO INSERT FORM DATA INTO A MYSQL DATABASE USING PHP
This article assumes that you have a basic understanding of html and css, and you already know how to run a php script. This is a really easy if you follow these steps:
  1. Create a html form in your index.php
  2. Create database
  3. Create the table
  4. Create a connection to your database 
  5. Insert your data
  6. …aaand you’re done!


CREATE HTML FORM IN YOUR INDEX.PHP
Create a file called index.php in your local host directory and create a simple form in this page.

“ <form class="" action="index.php" method="post">
      <label for="firstname">Firstname</label>
      <input type="text" name="firstname" required placeholder="firstname"/><br><br>
      <label for="lastname">Lastname</label> 
<input type="text" name="lastname" required placeholder="lastname"/><br><br> 
      <label for="email">Phone Number</label>
      <input type="text" name="number" required placeholder="enter phone number"><br><br>

      <button type="submit" name="submit">Sign up</button> <br><br>
    </form> </body>”
Activate WAMP, LAMP or XAMMP server and enter “localhost” into your browser. You should see something like the image below:



CREATE DATABASE
To create a database, enter “localhost/phpmyadmin” into your browser


On the login page, enter “root” as the username if you haven’t used phpMyAdmin before. Otherwise, you can enter any other username that you may have created.
By default, the password should be left empty but if you have changed your password before enter the correct password.



On the left side of the phpMyAdmin page is a list of all the databases present on your server.
Click New and enter a name for your database. Note that
 I have named mine “Learning_insert”, change the collation to “utf8_unicode_ci” and then click “create”





CREATE THE TABLE
When the database is created you would be directed to a create table page, this is where we would create an empty table that we would fill up with data from our form.
Enter a name name a set the “number of colums” to 3. The reason for this is we’d be passing three sets of data (firstname, lastname, phonenumber) from our form to our db. Now click “go”.
Fill up the “Name” and set the “type” to “varchar” and the “length” to “255” set the storage engine to “innoDB” and the click save.




At this point, you have successfully created a database and a table.
You can view the content of your db by clicking the database name and the table. Ours is currently empty.


CREATE A CONNECTION TO YOUR DATABASE
Return to your index.php file and and add a php tag. All php scripts must be written in a php tag.
“<?php ?>”
A simple connection to our database “learning_insert” can be created using the php script below
“<head>
<?php
  //setting connection parameters
  CONST DBHOST = "localhost";
  CONST DBUSER = "root";  //or whichever username you created
  CONST PASSWORD = ""; //password is empty by default, enter yours if you have one
  CONST DBNAME = "learning_insert";

  //setting up connection
  $conn = mysqli_connect(DBHOST, DBUSER, PASSWORD, DBNAME);

  //confirm connection
  if(mysqli_connect_errno()){
   //if connection fails
    die('Failed to connect to db'.mysqli_connect_error().'('.mysqli_connect_errno().')');
  }else {
    echo  "connection successful";
  }
?>
</head>”
If you’re getting any errors, remember google is your friend. If your work is successful, you should see something like this. Note that "connection successful" would always be echoed to the screen. This is a useful testing feature, however, you can turn it off by commenting out the echo success message.

INSERT DATA
The first step to inserting data into the db is to check if the submit button has been pressed, if this condition is met we set up the variables that would be inserted into the db. This can be achieved by adding the following php code snippet to the php script in our header.
if (isset($_POST['submit'])){

        //if the submit button is pressed create variables
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $phonenumber = $_POST['number'];
}”
Finally, the data would be inserted into the db using the php code below



$sql =  "INSERT INTO `user_info ` (firstname, lastname, phonenumber) VALUES ('{$firstname}', '{$lastname}', '{$phonenumber}')"; //ensure  that this line of code is on the same line

if($insert = mysqli_query($conn, $sql)) {
                     echo “You have inserted data succesfully”;
                   }else{
                     echo "data not saved".mysqli_error($conn);
                   }



In the end, your full code should look just like this.

“<!doctype html>
<head>
<?php

  //setting connection parameters
  CONST DBHOST = "localhost";
  CONST DBUSER = "root";  //or whichever username you created
  CONST PASSWORD = ""; //password is empty by default, enter yours if you have one
  CONST DBNAME = "learning_insert";

  //setting up connection
  $conn = mysqli_connect(DBHOST, DBUSER, PASSWORD, DBNAME);

  //confirm connection
  if(mysqli_connect_errno()){

    die('Failed to connect to db'.mysqli_connect_error().'('.mysqli_connect_errno().')');
  }else {
    echo  "connection successful";
  }
  if (isset($_POST['submit'])){

        //if the submit button is pressed create variables
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $phonenumber = $_POST['number'];

$sql =  "INSERT INTO `user_info ` (firstname, lastname, phonenumber) VALUES ('{$firstname}', '{$lastname}', '{$phonenumber}')";
                       
     if($insert = mysqli_query($conn, $sql)) {
            echo "you have inserted data successfully";
            }else{
                   $echo = "data not saved".mysqli_error($conn);
                }

}

?>
</head>
<body>
    <h1>This is the sign up page</h1>
    <br><br>
    <form class="" action="index.php" method="post">
      <label for="firstname">Firstname</label>
      <input type="text" name="firstname" required placeholder="firstname"/><br><br>
      <label for="lastname">Lastname</label>
              <input type="text" name="lastname" required placeholder="lastname"/><br><br>
      <label for="email">Phone Number</label>
      <input type="text" name="number" required placeholder="enter phone number"><br><br>

      <button type="submit" name="submit">Sign up</button> <br><br>
    </form>
</body>”

….AAAND YOU’RE DONE
At this stage our database is connected to index.php. We can now test if everything is working fine.

On clicking the sign up button, you’ll see a success message

Now, let’s check our database and confirm that the information has been stored successfully.

No comments:

Post a Comment