banner



How To Connect Html Register Form To Mysql Database With Php

php contact form

A PHP contact form allows users to communicate with website administrators. It allows them to ship queries to the site owners about relevant services or features. Using the contact form, web administrators are able to manage their business organization emails. In one case in that location is an active contact form available, it can generate queries. It easily gets connected with the database, thus providing complete record and details almost the users who are willing to contact and send their queries to website administrators.

  1. Prerequisites
  2. Create the Contact Form HTML
  3. Configure the MySQL Database
  4. Create the PHP Contact Class Script
  5. Post Method
  6. Form Captcha
  7. PHP Contact Class with Captcha
    1. Contact Course Captcha Validation
    2. Captcha Refresh
  8. PHP Captcha Paradigm
  9. Form Handler Library
  10. Last Words

Prerequisites

To create a uncomplicated PHP contact course with MySQL, I assume that y'all take a PHP application installed on a web server. My setup is:

  • PHP vii.one
  • MySQL
  • Jquery/Ajax

To make sure that that I don't go side-tracked by server level issues, I decided to host PHP awarding on Cloudways managed servers because the platform offers a powerful PHP optimized environment. In addition, I don't have to deal with server management hassles and thus focus on the core idea of this tutorial.

Stop Wasting Time on Servers

Cloudways handle server direction for you so you lot can focus on creating dandy apps and keeping your clients happy.

You tin also try out Cloudways for free by signing upward an account on the platform post-obit this GIF:

Cloudways Installation

Create the Contact Form HTML

Create the contact form HTML as shown beneath with validation and salvage it with .php extension. Value which will be written betwixt the double quotes in aspect Name like name="u_name" in input tags work equally a variable name. These attributes will incorporate the data from the class that we will use to save in our database . There are two methods to ship your form data to your PHP page: Become and Mail. I will be using POST as information technology hides the user data and at that place is no limit to send information. If you don't have the fourth dimension to dive deep in technicalities, you can employ online forms that are pre-designed according to professional course design standards.

Note: For styling yous tin can use your ain CSS and also use Bootstrap Classes for better styling.

!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.iii.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="bearding"> <fashion>  #loading-img{ brandish:none; }  .response_msg{ margin-height:10px; font-size:13px; background:#E5D669; color:#ffffff; width:250px; padding:3px; display:none; }  </style> </head> <torso>  <div class="container"> <div class="row">  <div course="col-md-8"> <h1><img src="Research.png" width="80px">Like shooting fish in a barrel Contact Form With Ajax MySQL</h1> <form name="contact-form" action="" method="post" id="contact-form"> <div course="form-group"> <label for="Proper name">Name</label> <input type="text" form="form-control" proper name="your_name" placeholder="Proper noun" required> </div> <div class="grade-group"> <label for="exampleInputEmail1">Email address</characterization> <input blazon="email" form="grade-control" name="your_email" placeholder="Email" required> </div> <div class="form-group"> <characterization for="Phone">Phone</label> <input type="text" form="course-control" name="your_phone" placeholder="Phone" required> </div> <div class="form-grouping"> <label for="comments">Comments</label> <textarea name="comments" form="class-control" rows="3" cols="28" rows="5" placeholder="Comments"></textarea>  </div>  <button type="submit" grade="btn btn-primary" proper noun="submit" value="Submit" id="submit_form">Submit</button> <img src="img/loading.gif" id="loading-img"> </form>  <div class="response_msg"></div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.xi.ii/jquery.min.js"></script> <script> $(document).ready(function(){ $("#contact-form").on("submit",function(e){ e.preventDefault(); if($("#contact-grade [name='your_name']").val() === '') { $("#contact-form [proper name='your_name']").css("border","1px solid red"); } else if ($("#contact-form [name='your_email']").val() === '') { $("#contact-form [proper name='your_email']").css("border","1px solid scarlet"); } else { $("#loading-img").css("display","cake"); var sendData = $( this ).serialize(); $.ajax({ type: "POST", url: "get_response.php", data: sendData, success: office(data){ $("#loading-img").css("display","none"); $(".response_msg").text(data); $(".response_msg").slideDown().fadeOut(3000); $("#contact-form").find("input[type=text], input[type=email], textarea").val(""); }  }); } });  $("#contact-form input").blur(function(){ var checkValue = $(this).val(); if(checkValue != '') { $(this).css("edge","1px solid #eeeeee"); } }); }); </script> </torso> </html>

Configure the MySQL Database

The next step is to setup and configure the MySQL database. For this, fire upward the Cloudways Database director and create a table 'contact_form_info', with the fields id , name , email , phone,comments .

Next, create config.php that will exist used to fix the connectedness between the PHP app and the database. Once the file has been created, open it and paste the following code in it:

<?php $host = "localhost"; $userName = "fyrhp"; $password = "RTDE"; $dbName = "fyrhp";  // Create database connection $conn = new mysqli($host, $userName, $password, $dbName);  // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>

Yous might also similar: How to Connect to a Remote MySQL Database

Now let's create a file get_response.php and paste the post-obit code in it:

<?php  require_once("config.php"); if((isset($_POST['your_name'])&& $_POST['your_name'] !='') && (isset($_POST['your_email'])&& $_POST['your_email'] !='')) {  require_once("contact_mail.php");        
$yourName = $conn->real_escape_string($_POST['your_name']); $yourEmail = $conn->real_escape_string($_POST['your_email']); $yourPhone = $conn->real_escape_string($_POST['your_phone']); $comments = $conn->real_escape_string($_POST['comments']);  $sql="INSERT INTO contact_form_info (name, email, phone, comments) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."', '".$comments."')";   if(!$consequence = $conn->query($sql)){ die('There was an error running the query [' . $conn->fault . ']'); } else { echo "Give thanks yous! Nosotros will contact you lot shortly"; } } else { echo "Please fill up Name and Email"; } ?>

In this PHP code, I take used the POST method for submitting the contact form data to the server. I volition use two PHP global methods, $_REQUEST and $_POST to retrieve and save the contact course data in the server local variable.

The difference between these ii is that $_REQUEST can retrieve data from both methods i.e. Go and Postal service. However, $_POST can just receive data from the POST method.

Hither is what the PHP contact grade script looks in action:

Mail Method

I besides create a file contact_mail.php for mail in which send your contact grade data on your mail hands.

<?php $toEmail = "[email protected]"; $mailHeaders = "From: " . $_POST["your_name"] . "<". $_POST["your_email"] .">\r\north"; if(postal service($toEmail, $_POST["comments"], $_POST["your_phone"], $mailHeaders)) { echo"<p course='success'>Contact Post Sent.</p>"; } else { echo"<p class='Mistake'>Problem in Sending Mail.</p>"; } ?>

Yous might too similar: How to Ship Email in PHP

Grade Captcha

You can utilize Captcha code in a form to ensure that the form is submitted with manual intervention without using whatever tools.

PHP Contact Form with Captcha

To develop contact form with captcha, let'south outset with the following HTML lawmaking. In this lawmaking, I will put a PHP file link into the prototype tag with the name of captcha.php.

<div>  <label>Captcha</label>  <span id="captcha-info" class="info"></bridge><br/>  <input type="text" name="captcha" id="captcha" class="demoInputBox"><br>  </div>  <div>  <img id="captcha_code" src="captcha.php" />  <push button name="submit" grade="btnRefresh" onClick="refreshCaptcha();">Refresh Captcha</push>  </div>

Contact Form Captcha Validation

For Captcha field validation, you can paste the following lawmaking in <script> tag. Using this code, you lot can set jQuery validation for captcha form validation.

if(!$("#captcha").val()) {  $("#captcha-info").html("(required)");  $("#captcha").css('background-color','#FFFFDF');  valid = false;  }

Captcha Refresh

This uncomplicated jQuery script will refresh PHP captcha code, and recreate the epitome with the new lawmaking. This new image will be set up every bit captcha paradigm source.

function refreshCaptcha() {  $("#captcha_code").attr('src','captcha.php');  }

PHP Captcha Epitome

PHP uses a office called PHP rand() to generate a random number. Using md5(), you can encrypt the number and carve up it into 6-character captcha lawmaking. The code is non merely added to the PHP session merely also added as a source of captcha image using PHP GD function.

session_start();  $random_alpha = md5(rand());  $captcha_code = substr($random_alpha, 0, six);  $_SESSION["captcha_code"] = $captcha_code;  $target_layer = imagecreatetruecolor(seventy,xxx);  $captcha_background = imagecolorallocate($target_layer, 255, 160, 119);  imagefill($target_layer,0,0,$captcha_background);  $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);  imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);  header("Content-type: image/jpeg");  imagejpeg($target_layer);

Grade Handler Library

You can also perform captcha and grade validation past using Class Handler library. Check the following example:

employ FormGuide\Handlx\FormHandler;  $demo = new FormHandler();  $validator = $demo->getValidator();  $validator->fields(['name','email'])->areRequired()->maxLength(l);  $validator->field('email')->isEmail();  $validator->field('message')->maxLength(6000)  $demo->requireCaptcha();

Final Words

In this tutorial, I demonstrated creating a PHP contact course using HTML, AJAX, jQuery and MySQL. Here is a live demo of thePHP contact class lawmaking in action. I've as well given a cursory overview virtually captcha form, and why yous must use information technology in contact course. The article non only demonstrates how to setup captcha in a contact form, but also defines how to setup its validation using the script tag. Furthermore, you can also utilize Grade Handler library to integrate captcha validation within the course.

Yet, if you take some more than questions regarding captcha integration in the contact course, or want to share some of your tips on the topic, experience free to write downwards your suggestions in the comments section below.

Q. How do I code a contact grade in PHP ?

A: You'll need to create an HTML form that POSTs your PHP script that will handle the form submission. Each of your form fields/inputs should have an advisable name, such as electronic mail, every bit you will use these to reference PHP information.

The PHP volition need to capture the POST data (e.g., $_POST['email']) and use the mail service() function to send a bulletin that includes the desired output in the message body.

Q. Do you need PHP for the contact form ?

A: Contact form in PHP is i piece of website that you will get to know as a web developer. This is commonplace for users of a website to start a conversation with a seller or author, company, and freelancer.

Q. How practise I create a contact the states form in HTML and PHP ?

A: You'll need to create an HTML form that POSTs your PHP script that will handle the grade submission. Each of your course fields/inputs should have an appropriate name, you can recollect the value of a particular class field by passing its proper noun to the $_POST superglobal assortment, and display each field value using echo() statement.

Share your opinion in the annotate section. Annotate NOW

Share This Article

Client Review at

"Cloudways hosting has ane of the all-time client service and hosting speed"

Sanjit C [Website Developer]

Ahmed Khan

Ahmed was a PHP community skilful at Cloudways - A Managed PHP Hosting Deject Platform. He is a software engineer with extensive noesis in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at [electronic mail protected]

How To Connect Html Register Form To Mysql Database With Php,

Source: https://www.cloudways.com/blog/custom-php-mysql-contact-form/

Posted by: brownlizeatied.blogspot.com

0 Response to "How To Connect Html Register Form To Mysql Database With Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel