How to connect HTML Registration Form using PHP and MySQL

Learn, How to connect HTML Registration Form to MySQL Database with PHP with simple coding and easy video.
First, you have to make a form using HTML code which I provide below.

HTML form (form.html)

<!DOCTYPE HTML>
<html>
<head>
  <title>Register Form</title>
</head>
<body>
 <form action="insert.php" method="POST">
  <table>
   <tr>
    <td>Name :</td>
    <td><input type="text" name="username" required></td>
   </tr>
   <tr>
    <td>Password :</td>
    <td><input type="password" name="password" required></td>
   </tr>
   <tr>
    <td>Gender :</td>
    <td>
     <input type="radio" name="gender" value="m" required>Male
     <input type="radio" name="gender" value="f" required>Female
    </td>
   </tr>
   <tr>
    <td>Email :</td>
    <td><input type="email" name="email" required></td>
   </tr> 
   <tr>
    <td>Phone no :</td>
    <td>
     <select name="phoneCode" required>
      <option selected hidden value="">Select Code</option>
      <option value="977">977</option>
      <option value="978">978</option>
      <option value="979">979</option>
      <option value="973">973</option>
      <option value="972">972</option>
      <option value="974">974</option>
     </select>
     <input type="phone" name="phone" required>
    </td>
   </tr>
   <tr>
    <td><input type="submit" value="Submit" name="submit"></td>
   </tr>
  </table>
 </form>
</body>
</html>

Inside the above code, you can see <form action="insert.php" method="POST">where, in action, I write insert.php which means we are sending our form data to insert.php.

The output of the above code

How to connect HTML Register Form to MySQL Database with PHP
Registration form in HTML

Server-side code (insert.php)

<?php
if (isset($_POST['submit'])) {
    if (isset($_POST['username']) && isset($_POST['password']) &&
        isset($_POST['gender']) && isset($_POST['email']) &&
        isset($_POST['phoneCode']) && isset($_POST['phone'])) {
        
        $username = $_POST['username'];
        $password = $_POST['password'];
        $gender = $_POST['gender'];
        $email = $_POST['email'];
        $phoneCode = $_POST['phoneCode'];
        $phone = $_POST['phone'];

        $host = "localhost";
        $dbUsername = "root";
        $dbPassword = "";
        $dbName = "test";

        $conn = new mysqli($host, $dbUsername, $dbPassword, $dbName);

        if ($conn->connect_error) {
            die('Could not connect to the database.');
        }
        else {
            $Select = "SELECT email FROM register WHERE email = ? LIMIT 1";
            $Insert = "INSERT INTO register(username, password, gender, email, phoneCode, phone) values(?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($Select);
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->bind_result($resultEmail);
            $stmt->store_result();
            $stmt->fetch();
            $rnum = $stmt->num_rows;

            if ($rnum == 0) {
                $stmt->close();

                $stmt = $conn->prepare($Insert);
                $stmt->bind_param("ssssii",$username, $password, $gender, $email, $phoneCode, $phone);
                if ($stmt->execute()) {
                    echo "New record inserted sucessfully.";
                }
                else {
                    echo $stmt->error;
                }
            }
            else {
                echo "Someone already registers using this email.";
            }
            $stmt->close();
            $conn->close();
        }
    }
    else {
        echo "All field are required.";
        die();
    }
}
else {
    echo "Submit button is not set";
}
?>

Explaining server-side code

Declaring variables and check, are they empty or not

In line 3, we check ( $username, $password, $gender, $email, $phoneCode and $phone) are not set or not. If these are not set then we go all the way down to line 55. If these are set then code from line 7 will execute.

By using a code from line 7 to 12, we are grabbing data from HTML form and store it into PHP variables ( $username, $password, $gender, $email, $phoneCode and $phone).

Make a database connection

From line 14 to line 17 we declare a variables ( $host, $dbUsername, $dbPassword and $dbname) and assign a value for connecting a database.

Then, in line 19 we make a database connection and assign it into a $conn

After that, in line 21 we check that, is our database connected. If there is no connection then we display error and exit. If a database is connected we continue from line 24.

Declare SQL query in a variable

In, line 25, there is a SELECT query to select data from a database and in line 26, there is an INSERT query to insert user record into a database.

Using the prepared statement

After that, we are using the prepared statement to run our query and protect our database from SQL injection.

28. We Run SELECT query

29. We are Passing an email value into a SELECT query and we define “s” because email is a string. You can see below and know, which parameter you should use your data type.

  • i – integer
  • d – double
  • s – string
  • b – BLOB

You can learn more about above i, d, s, and b in Prepared Statements

In a SELECT query, we are selecting only email so, in line 31, we catch that email value.

In, line 34, we store the number of row in a variable  $rnum from our result.

Insert user’s data

Then in, line 36, we check is our result contains 0 rows, if yes then we continue running our coding if not, we jump into line 48 and give a message “Someone already registers using this email”.

If there are zero rows in a result then that means, this user’s data is not already stored in our database. So we can store this record in our database as a new user. But first, we need to close a prepared statement for the SELECT query and start a prepared statement for an INSERT query.

And after data is inserted into a database, we give a message “New record inserted successfully”. And, that’s it.

This is how you connect how to create registration form in HTML with database.

You may also like to read:

4.6 15 votes
Article Rating
Subscribe
Notify of
88 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Nawaraj Shah
4 years ago

Paste your whole code

Unknown
4 years ago

it goes all ok but when i go to my localhost/phpmyadmin the data is not there

Unknown
4 years ago

the code went wrong, this is the one:

prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sssi", $username, $password, $email, $phone);
$stmt->execute();
echo "Conta criada com sucesso";
}
else {
echo "Alguem ja registrou este e-mail";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>
Last edited 2 years ago by Nawaraj Shah
daisy
4 years ago

please help me out …im getting this error

Fatal error: Call to a member function bind_param() on a non-object in C:xampphtdocsminiprojectinsert1.php on line 26

please help me ,i need to submit my project tomorrow.

daisy
4 years ago
prepare($SELECT);
 $stmt->bind_param("s", $EmailId);
 $stmt->execute();
 $stmt->bind_result($EmailId);
 $stmt->store_result();
 $rnum = $stmt->num_rows;
 if ($rnum==0) {
 $stmt->close();
 $stmt = $conn->prepare($INSERT);
 $stmt->bind_param("sssssi",$Customername, $EmailId, $ConfirmEmailId, $City, $Country, $Mobilenumber);
 $stmt->execute();
 echo "New record inserted successfully";
 }

else {
 echo "Someone already registered using this EmailId";
 }
 $stmt->close();
 $conn->close();
 }
} else {
 echo "All field are required";
 die();
}
?>
Last edited 2 years ago by Nawaraj Shah
Nawaraj Shah
4 years ago

first you have to check that your MySQL code is perfectly work on you PHPMyadmin

Nawaraj Shah
4 years ago

paste your whole code

Unknown
4 years ago

help pls

Unknown
4 years ago

Error: INSERT INTO account (username, password) values ('asdasdin' , 'asdasd') Unknown column 'username' in 'field list'

Nawaraj Shah
4 years ago

you can find on youtube

Unknown
4 years ago

How to run php..
I'm asking you every where I just need to make my website not carrier

swapnali redij
4 years ago

please help-…after 'New record inserted successfully' data not showing in database.

Nawaraj Shah
4 years ago

For your first question
if you dont use hidden, then user can re select that default option. And if we dont want to store it in a database then why let them to select that option. If the default option only selected and no other option is selected then user will unable to submit that data to the server. But you can use this as your need.

For your second question
Make it more clear, i dont get what you want to say.

Unknown
4 years ago

Ah ok, thank you! Question 1) …so the "selected" determine what is shown by default, the "hidden" means that if no option is selected by the user, nothing will be send to the database right?So why do we need to set a value to this fake option if it's "hidden" anyway.Question 2) in my case, I want to let the user decide to leave the field empty is not option suit him/her. So far, I do that by having an option called "Empty field" with a value="". Is there a better / more elegant way to do that?(BTW, thanks for… Read more »

Nawaraj Shah
4 years ago

Before select any option it shows "Select Option" and after select any option then we can not select "Select Option" anymore.

Unknown
4 years ago

I don't understand what is this:

option selected hidden value=""

Thanks you

Nawaraj Shah
4 years ago

My suggestion is first you have to learn about php

Unknown
4 years ago

when I register and submit the form, it direct me to a page with the insert.php coding?

ADOL TECH LIFE
4 years ago

hello Niraj suna milay error pai rachu as ma $stmt->bind_param("s", $email);
description: Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:xampphtdocswebsiteinsert.php:26 Stack trace: #0 {main} thrown in C:xampphtdocswebsiteinsert.php on line 26

Unknown
4 years ago

Very good

Nawaraj Shah
4 years ago

Thanks for your great help

Nawaraj Shah
4 years ago

Thanks for your support

Nawaraj Shah
4 years ago

Thanks for your support

Rana Rohit
4 years ago

Even I had the same issue, this problem is because you ain't executing the problem well. Run the code in the following way: Here's how to run the code:I hope you already had installed XAMPP, else do it. After installation, copy the html & php file to "htdocs" folder under xampp directory of C: Start the xampp control panel & on the Apache and MYSQL from it.Create the said database & table.Now go and run the html file in browser, you are good to go. Hopefully it helps, and make sure that the database, & table name are same in… Read more »

Rana Rohit
4 years ago

this problem is because you ain't executing the problem well. Run the code in the following way: Here's how to run the code:I hope you already had installed XAMPP, else do it. After installation, copy the html & php file to "htdocs" folder under xampp directory of C: Start the xampp control panel & on the Apache and MYSQL from it.Create the said database & table.Now go and run the html file in browser, you are good to go. Hopefully it helps, and make sure that the database, & table name are same in the program as well as in… Read more »

Rana Rohit
4 years ago

Run the code in the following way: Don't be that rude Nawaraj, Here's how to run the code:I hope you already had installed XAMPP, else do it. After installation, copy the html & php file to "htdocs" folder under xampp directory of C: Start the xampp control panel & on the Apache and MYSQL from it.Create the said database & table.Now go and run the html file in browser, you are good to go. Hopefully it helps, and make sure that the database, & table name are same in the program as well as in phpadmin.Moreover, make sure that the… Read more »

Unknown
4 years ago

Don't be that rude Nawaraj,

Here's how to run the code:
I hope you already had installed XAMPP, else do it.

After installation, copy the html & php file to "htdocs" folder under xampp directory of C:

Start the xampp control panel & on the Apache and MYSQL from it.
Create the said database & table.
Now go and run the html file in browser, you are good to go.

Hopefully it helps,

jack malhotra
4 years ago

MYSQL database not showing inserted data from HTML form
sir Please help what can i do

My record is inserted in database but not showing

prepare($SELECT);
 $stmt->bind_param("s", $Email_id);
 $stmt->execute();
 $stmt->bind_result($Email_id);
 $stmt->store_result();
 $rnum = $stmt->num_rows;

if ($rnum==0) 
 {
 $stmt->close();
 $stmt = $conn->prepare($INSERT);
 $stmt->bind_param("ssssssssis", $First_name, $Lirst_name, $Username, $Password, $Confirm_password, $Gender, $Email_id, $PhoneCode, $Mobile_no, $Address);
 $stmt->execute();
 echo "New record inserted sucessfully";
 } 
 else 
 {
 echo "Someone already register using this email";
 }
 $stmt->close();
 $conn->close();
 }

}
?>
Last edited 2 years ago by Nawaraj Shah
Nawaraj Shah
4 years ago

YouTube is a database but you have to create a table called register with a columns username, password, gender, email, phoneCode, phone.

Shafii
4 years ago

What is the content of the YouTube database?

Nawaraj Shah
4 years ago

First learn how to run php code

iman zakhwan
4 years ago

Why when I register and submit the form, it direct me to a page with the insert.php coding?

amogh mulge
amogh mulge
Reply to  iman zakhwan
4 years ago

dont open html file directly.open through localhost/foldername(inwhich)htmlfile/filename.html

soner
soner
Reply to  amogh mulge
3 years ago

could you explain a little bit more please ?

i cant record the data..

insert.php is openimg on google page..

Nawaraj Shah
4 years ago

Past your code herre

pankaj R yadav
4 years ago

Warning: mysqli::mysqli(): (HY000/2002): No connection could be made because the target machine actively refused it. in C:wampwwwform1insert.php on line 15

what is thise please help me

YGO PRO
4 years ago
prepare($SELECT);
 $stmt->bind_param("s", $email);
 $stmt->execute();
 $stmt->bind_result($email);
 $stmt->store_result();
 $rnum = $stmt->num_rows;
 if ($rnum==0) {
 $stmt->close();
 $stmt = $conn->prepare($INSERT);
 $stmt->bind_param("ssssssii", $username, $password, $tpnumber, $gender, $group, $email, $phoneCode, $phone);
 $stmt->execute();
 echo "Registration success!!";
 } else {
 echo "Someone already register using this email";
 }
 $stmt->close();
 $conn->close();
 }
} else {
 echo "All field are required";
 die();
}

?>
Last edited 2 years ago by Nawaraj Shah
YGO PRO
4 years ago

This comment has been removed by the author.

YGO PRO
4 years ago

Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in /storage/ssd5/928/6222928/public_html/04_Registration.php:34 Stack trace: #0 {main} thrown in /storage/ssd5/928/6222928/public_html/04_Registration.php on line 34

ughh, helppp

xhunet milan
4 years ago

hellow i have a error please hep me it shown
Notice: Undefined index: username in C:xampphtdocsformainsert.php on line 2

Notice: Undefined index: password in C:xampphtdocsformainsert.php on line 3

Notice: Undefined index: gender in C:xampphtdocsformainsert.php on line 4

Notice: Undefined index: email in C:xampphtdocsformainsert.php on line 5

Notice: Undefined index: phoneCode in C:xampphtdocsformainsert.php on line 6

Notice: Undefined index: phone in C:xampphtdocsformainsert.php on line 7
All field are required

Please help me

Nawaraj Shah
4 years ago

Past your code here

Team Cyber Python
5 years ago

Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in F:Xampphtdocssampleinsert.php:24 Stack trace: #0 {main} thrown in F:Xampphtdocssampleinsert.php on line 24

Arslan Majid
5 years ago

Parse error: syntax error, unexpected '||' (T_BOOLEAN_OR) in C:xampphtdocssunnyinsert.php on line 11

Adebayo kayode
Adebayo kayode
Reply to  Arslan Majid
4 years ago

Fatal error: Uncaught Error: Call to a member function bind_param() on bool in C:\xampp\htdocs\Antbs\insert.php:30 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Antbs\insert.php on line 30

repeater
4 years ago

Thіs design is wickeԀ! You obviously know how
to keep a reader entеrtained. Between your wit and your videos, I was almost moved to start mʏ own blog (well,
almost…HaHa!) Excellent jоb. I really enjoyed what you had to say,
and more than that, how you presenteⅾ it. Too cool!

wie mache ich ein backup von meinem iphone
4 years ago

Fantastic postings, Cheers.

Jaya
4 years ago

You are doing a great job. I would like to appreciate your work for good accuracy
Regards,
PHP Training in Chennai | PHP Course in Chennai

Subash
Subash
4 years ago
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in E:\xampp\htdocs\jobsite\login\registed.php:23 Stack trace: #0 {main} thrown in E:\xampp\htdocs\jobsite\login\registed.php on line 23
Last edited 2 years ago by Nawaraj Shah
Nouman Rasheed
Nouman Rasheed
4 years ago

i am working in wammp and actio is not woring when i click on submit it opens the php code instead of submitting the data….any solution ??

ULA
ULA
Reply to  Nouman Rasheed
4 years ago

NOUMAN RASHEED
i have the same problem….did you find any solution plz???

Zainul Abid
4 years ago

what is the data type for select option in mysql (non-numeric)

Kath
Kath
4 years ago

Hi I tried everything that you have said including copying the php and html files in htdocs, but everytime I clicked Insert button, it goes only to my insert.php page. Can you please help me? Thank you in advance.

saroj
saroj
4 years ago

thanks