Signup form using PHP and MySQL Database
Last Updated :
09 Sep, 2020
The task is to create and design a sign-up form in which if the user enters details, the HTML form data are inserted into our MySQL server database.
Approach:
- First task is that we have to create our MySQL server Database and a Table according to our requirements.
- We connect our MySQL server Database using PHP mysqli_connect() function which takes four arguments, i.e. our "servername", "username", "password" and "database".
Note: No CSS code is used here as we are using Bootstrap in the following PHP code. You can apply CSS and style in your web page as per your own application requirement.
PHP code to create Database connection: First and the most basic step is to create a Database connection. The PHP file name used here is "dbconnect.php" and the database name used is "geeksforgeeks".
php
$servername = "localhost";
$username = "root";
$password = "";
$database = "geeksforgeeks";
// Create a connection
$conn = mysqli_connect($servername,
$username, $password, $database);
// Code written below is a step taken
// to check that our Database is
// connected properly or not. If our
// Database is properly connected we
// can remove this part from the code
// or we can simply make it a comment
// for future reference.
if($conn) {
echo "success";
}
else {
die("Error". mysqli_connect_error());
}
?>
"users" table is created using MySQL phpMyAdmin tool as shown below.
PHP code to design sign-up form: Now when we have successfully connected to our Database, it is time to create the Signup form for the users. The following PHP code demonstrates the sign-up form. The MySql database table name used is "users".
php
$showAlert = false;
$showError = false;
$exists=false;
if($_SERVER["REQUEST_METHOD"] == "POST") {
// Include file which makes the
// Database Connection.
include 'dbconnect.php';
$username = $_POST["username"];
$password = $_POST["password"];
$cpassword = $_POST["cpassword"];
$sql = "Select * from users where username='$username'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);
// This sql query is use to check if
// the username is already present
// or not in our Database
if($num == 0) {
if(($password == $cpassword) && $exists==false) {
$hash = password_hash($password,
PASSWORD_DEFAULT);
// Password Hashing is used here.
$sql = "INSERT INTO `users` ( `username`,
`password`, `date`) VALUES ('$username',
'$hash', current_timestamp())";
$result = mysqli_query($conn, $sql);
if ($result) {
$showAlert = true;
}
}
else {
$showError = "Passwords do not match";
}
}// end if
if($num>0)
{
$exists="Username not available";
}
}//end if
?>
"width=device-width, initial-scale=1,
shrink-to-fit=no">
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity=
"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous">
if($showAlert) {
echo ' alert-dismissible fade show" role="alert">
Success! Your account is
now created and you can login.
';
}
if($showError) {
echo ' alert-dismissible fade show" role="alert">
Error! '. $showError.'
';
}
if($exists) {
echo ' alert-dismissible fade show" role="alert">
Error! '. $exists.'
';
}
?>
Output:
- Sign-up form:
- After successful user login:
- After invalid user login:
Similar Reads
How to create admin login page using PHP? In this article, we will see how we can create a login page for admin, connected with the database, or whose information to log in to the page is already stored in our database. Follow the steps to create an admin login page using PHP: Approach: Make sure you have XAMPP or WAMP installed on your w
4 min read
Signup form using PHP and MySQL Database The task is to create and design a sign-up form in which if the user enters details, the HTML form data are inserted into our MySQL server database. Approach: First task is that we have to create our MySQL server Database and a Table according to our requirements. We connect our MySQL server Databas
4 min read
Online Group Chat application using PHP Prerequisites:Â Technical knowledge: HTMLCSSJavascript (basics)PHP (Database connectivity)SQL queries Softwares to be installed: XAMPP server: This is a free software which contains web server Apache, Database management system for MySQL (or MariaDB). It can be downloaded for free from the official s
9 min read
How to Resize JPEG Image in PHP ? Why do we need to resize images? In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those c
2 min read
How to make PDF file downloadable in HTML link using PHP ? In web development, it is common to provide users with downloadable resources, such as PDF files. If you want to create a downloadable PDF link using HTML and PHP, this article will guide you through the process of making a PDF file downloadable when the user clicks on a link. ApproachCreate an HTML
3 min read
How to extract img src and alt from html using PHP? Extraction of image attributes like 'src', 'alt', 'height', 'width' etc from a HTML page using PHP. This task can be done using the following steps. Loading HTML content in a variable(DOM variable). Selecting each image in that document. Selecting attribute and save it's content to a variable. Outpu
2 min read
Upload pdf file to MySQL database for multiple records using PHP We will upload multiple records to the database and display all the records from the database on the same page. In this article, we will see how we can upload PDF files to a MySQL database using PHP. Approach: Make sure you have XAMPP or WAMP installed on your machine. In this tutorial, we will be
7 min read
Mailer multiple address in PHP In this article, we will be demonstrating how we can send the mail to the multiple addresses from the database using the PHP. PHPMailer library is used to send any email safely from the unknown e-mail to any mail id using PHP code through XAMPP web-server for this project. Installation process for a
2 min read
Covid 19 Tracker Web App using PHP In this article, we will see how to create a web application for tracking the Covid19 using PHP. Our Covid19 Tracker app will give the latest information for the States and Union Territories of India about the following things.Number of Active Cases of Covid19.Number of Confirmed Cases of Covid19.Nu
3 min read
How to automatically start a download in PHP ? This post deals with creating a start downloading file using PHP. The idea is to make a download button which will redirect you to another page with the PHP script that will automatically start the download. Creating a download button: html
2 min read
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
min 4 words, max Words Limit:1000
Thank You!
Your suggestions are valuable to us.
');
// $('.spinner-loading-overlay').show();
let script = document.createElement('script');
script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js';
script.defer = true
document.head.appendChild(script);
script.onload = function() {
suggestionModalEditor() //to add editor in suggestion modal
if(loginData && loginData.premiumConsent){
personalNoteEditor() //to load editor in personal note
}
}
script.onerror = function() {
if($('.editorError').length){
$('.editorError').remove();
}
var messageDiv = $('
').text('Editor not loaded due to some issues');
$('#suggestion-section-textarea').append(messageDiv);
$('.suggest-bottom-btn').hide();
$('.suggestion-section').hide();
editorLoaded = false;
}
});
//suggestion modal editor
function suggestionModalEditor(){
// editor params
const params = {
data: undefined,
plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"],
}
// loading editor
try {
suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true })
suggestEditorInstance._createEditor("")
$('.spinner-loading-overlay:eq(0)').remove();
editorLoaded = true;
}
catch (error) {
$('.spinner-loading-overlay:eq(0)').remove();
editorLoaded = false;
}
}
//personal note editor
function personalNoteEditor(){
// editor params
const params = {
data: undefined,
plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"],
placeholderText: "Description to be......",
}
// loading editor
try {
let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true })
notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"")
$('.spinner-loading-overlay:eq(0)').remove();
editorLoaded = true;
}
catch (error) {
$('.spinner-loading-overlay:eq(0)').remove();
editorLoaded = false;
}
}
var lockedCasesHtml = `
You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`;
var badgesRequiredHtml = `
It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.However, you can still create improvements through the Pick for Improvement section.`;
jQuery('.improve-header-sec-child').on('click', function(){
jQuery('.improve-modal--overlay').hide();
$('.improve-modal--suggestion').hide();
jQuery('#suggestion-modal-alert').hide();
});
$('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked
$('.ContentEditable__root').text("");
$('.suggest-bottom-btn').html("Suggest changes");
$('.thank-you-message').css("display","none");
$('.improve-modal--improvement').hide();
$('.improve-modal--suggestion').show();
$('#suggestion-section-textarea').show();
jQuery('#suggestion-modal-alert').hide();
if(suggestEditorInstance !== null){
suggestEditorInstance.setEditorValue("");
}
$('.suggestion-section').css('display', 'block');
jQuery('.suggest-bottom-btn').css("display","block");
});
$('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown
if(loginData && loginData.isLoggedIn) {
$('body').append('
');
$('.spinner-loading-overlay').show();
jQuery.ajax({
url: writeApiUrl + 'create-improvement-post/?v=1',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
xhrFields: {
withCredentials: true
},
data: JSON.stringify({
gfg_id: post_id
}),
success:function(result) {
$('.spinner-loading-overlay:eq(0)').remove();
$('.improve-modal--overlay').hide();
$('.unlocked-status--improve-modal-content').css("display","none");
$('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank');
$('.create-improvement-redirection-to-write')[0].click();
},
error:function(e) {
showErrorMessage(e.responseJSON,e.status)
},
});
}
else {
if(loginData && !loginData.isLoggedIn) {
$('.improve-modal--overlay').hide();
if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) {
$('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click();
}
return;
}
}
});
$('.left-arrow-icon_wrapper').on('click',function(){
if($('.improve-modal--suggestion').is(":visible"))
$('.improve-modal--suggestion').hide();
else{
}
$('.improve-modal--improvement').show();
});
const showErrorMessage = (result,statusCode) => {
if(!result)
return;
$('.spinner-loading-overlay:eq(0)').remove();
if(statusCode == 403) {
$('.improve-modal--improve-content.error-message').html(result.message);
jQuery('.improve-modal--overlay').show();
jQuery('.improve-modal--improvement').show();
$('.locked-status--impove-modal').css("display","block");
$('.unlocked-status--improve-modal-content').css("display","none");
$('.improve-modal--improvement').attr("status","locked");
return;
}
}
function suggestionCall() {
var editorValue = suggestEditorInstance.getValue();
var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() {
return $(this).text().trim();
}).get().join(' ');
suggest_val = suggest_val.replace(/\s+/g, ' ').trim();
var array_String= suggest_val.split(" ") //array of words
var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val();
var error_msg = false;
if(suggest_val != "" && array_String.length >=4){
if(editorValue.length <= 2000){
var payload = {
"gfg_post_id" : `${post_id}`,
"suggestion" : `${editorValue}`,
}
if(!loginData || !loginData.isLoggedIn) // User is not logged in
payload["g-recaptcha-token"] = gCaptchaToken
jQuery.ajax({
type:'post',
url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/",
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType:'application/json',
data: JSON.stringify(payload),
success:function(data) {
if(!loginData || !loginData.isLoggedIn) {
grecaptcha.reset();
}
jQuery('.spinner-loading-overlay:eq(0)').remove();
jQuery('.suggest-bottom-btn').css("display","none");
$('#suggestion-section-textarea').hide()
$('.thank-you-message').css('display', 'flex');
$('.suggestion-section').css('display', 'none');
jQuery('#suggestion-modal-alert').hide();
},
error:function(data) {
if(!loginData || !loginData.isLoggedIn) {
grecaptcha.reset();
}
jQuery('.spinner-loading-overlay:eq(0)').remove();
jQuery('#suggestion-modal-alert').html("Something went wrong.");
jQuery('#suggestion-modal-alert').show();
error_msg = true;
}
});
}
else{
jQuery('.spinner-loading-overlay:eq(0)').remove();
jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000.");
jQuery('#suggestion-modal-alert').show();
jQuery('.ContentEditable__root').focus();
error_msg = true;
}
}
else{
jQuery('.spinner-loading-overlay:eq(0)').remove();
jQuery('#suggestion-modal-alert').html("Enter atleast four words !");
jQuery('#suggestion-modal-alert').show();
jQuery('.ContentEditable__root').focus();
error_msg = true;
}
if(error_msg){
setTimeout(() => {
jQuery('.ContentEditable__root').focus();
jQuery('#suggestion-modal-alert').hide();
}, 3000);
}
}
document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){
jQuery('body').append('
');
jQuery('.spinner-loading-overlay').show();
if(loginData && loginData.isLoggedIn) {
suggestionCall();
return;
}
// script for grecaptcha loaded in loginmodal.html and call function to set the token
setGoogleRecaptcha();
});
$('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked
$('body').append('
');
$('.spinner-loading-overlay').show();
// send this option via create-improvement-post api
jQuery.ajax({
url: writeApiUrl + 'create-improvement-post/?v=1',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
xhrFields: {
withCredentials: true
},
data: JSON.stringify({
gfg_id: post_id
}),
success:function(result) {
$('.spinner-loading-overlay:eq(0)').remove();
$('.improve-modal--overlay').hide();
$('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank');
$('.create-improvement-redirection-to-write')[0].click();
},
error:function(e) {
showErrorMessage(e.responseJSON,e.status);
},
});
});
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"