All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP Submit Form To Database And Email

Last Updated : Mar 11, 2024

PHP Submit Form To Database And Email

In this tutorial we will show you the solution of PHP submit form to database and email, as we know for stored html form data to database we need database connection then we can insert user input data to database table.

By using phpmailer via php we can easily achieve result. PHPMailer is a code library and used to send emails safely and easily via php code from a web server.

When sending emails directly by php code requires familiarity to SMTP standard protocol and related issues and vulnerability about email injection for spamming.

Step By Step Guide On PHP Submit Form To Database And Email :-

First we need to execute connection with database server then execute insertion query with html form of user input data to store on database table.

Here we used concept of PHPMailer code package those available in web browsers.

Phpmailer concept when we need means from any authenticated gmail account we can send email. Phpmailer has three php files.

PHPMailer.php supports several way of sending email messages like mail(), sendmail, qmail and direct dispatch from SMTP servers.

SMTP.php supports Sendmail() or other configured mail script on the server. On a hosted server the SMTP settings would have already been set.

Exception.php handles any type of php exceptions when errors occur.

Sendmail.php code also available we need to edit some detail (i.e) our SMTP server gmail address and password, here when submit button submitted by user all html form datas collected for send as email.

<?php include 'sendData.php'; ?>
<?php include 'sendemail.php'; ?>
<!DOCTYPE html>
<html>
  <head>
    <title>html form data to email</title>
  </head>
  <body>
    <!--alert messages start-->
    <?php echo $alert; ?>
    <!--alert messages end-->
    <center>
        <form class="contact" action="" method="post"><br><br>
          <input type="text" name="name" class="text-box" placeholder="Your Name" required><br><br>
          <input type="email" name="email" class="text-box" placeholder="Your Email" required><br><br>
          <textarea name="message" rows="5" placeholder="Your Message" required></textarea><br><br>
          <input type="submit" name="submit" class="send-btn" value="Send">
        </form>
    <center>
    <!--contact section end-->
    <script type="text/javascript">
    if(window.history.replaceState){
      window.history.replaceState(null, null, window.location.href);
    }
    </script>
  </body>
</html>

SendData.php

if(isset($_POST['submit'])){
$con=mysqli_connect('localhost','root','','user_records');
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])){
 $name=mysqli_real_escape_string($con,$_POST['name']);
 $email=mysqli_real_escape_string($con,$_POST['email']);
 $msg=mysqli_real_escape_string($con,$_POST['message']);
 $res=mysqli_query($con,"insert into contact(name,email,message) values('$name','$email','$msg')");
if($res){
echo "Inserted Successfully";
}
else{
echo "Not Inserted";
}
}

Sendmail.php

<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';
$mail = new PHPMailer(true);
$alert = '';
if(isset($_POST['submit'])){
  $name = $_POST['name'];
  $email = $_POST['email'];
  $message = $_POST['message'];
  try{
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'youremail@gmail.com'; // Gmail address which you want to use as SMTP server
    $mail->Password = 'youremailpassword'; // Gmail address Password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = '587';
    $mail->setFrom('youremail@gmail.com'); // Gmail address which you used as SMTP server
    $mail->addAddress('youranyemail@gmail.com'); // Email address where you want to receive emails (you can use any of your gmail address including the gmail address which you used as SMTP server)
    $mail->isHTML(true);
    $mail->Subject = 'Message Received (Contact Page)';
    $mail->Body = "<h3>Name : $name <br>Email: $email <br>Message : $message</h3>";
    $mail->send();
    $alert = '<div class="alert-success">
                 <span>Message Sent! Thank you for contacting us.</span>
                </div>';
  } catch (Exception $e){
    $alert = '<div class="alert-error">
                <span>'.$e->getMessage().'</span>
              </div>';
  }
}
?>
  1. <?php include 'sendemail.php'; ?> wherever you want to include block of code we can just include the file by ‘include()’ or ‘require()’ statements. In php file we can easily embed HTML code to format them and make them more user-friendly.
  2. <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in.
  3. The<html> tag is used to indicate the beginning of HTML document.
  4. As above shown <head> tag contain information about webpage and if need any external file those links are declared here. <title> tag is used for set the webpage title.
  5. Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If your not closed anyone of ending tag properly that is also affect the webpage result.
  6. <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
  7. <?php echo $alert; ?> in php prints the alert message for user clarification by ‘echo’. Echo used for print the statement in php.
  8. <center> tag used for align the whole contents into center of webpage. Within <form> tag form elements are defined with ‘post’ method for collects user inputs from html form.
  9. <input> tag type contains information of user name, mail id and submittion. <textarea> tag used for more line of text description it contain user message.
  10. In <script> tag window.history contains browser session history, a list of all the pages visited in current frame or window. replaceState() method modifies the current history entry and replaced with parameters of state object and URL.
  11. After submittion user filled details in form is replaced with empty and redirect to same web page.
  12. The sendData.php file executes their process it checks submit button clicks by user and all informations filled then only we can insert those data to database.
  13. For execute connection with server we used mysqli_connect() method for creates connection it contains ‘servername,username,password,databasename’. After confirmation of all details filled by user it stores all inputs to variables of ($name,$email,$msg).
  14. Using mysqli_query() method we executed insertion query to insert user inputs to our database ‘user_records’ table ‘contact’. If our query executed successfully then prints success message on webpage otherwise error message thrown on display of webpage browser.
  15. In sendmail.php file ‘use’ means tells a class to inherit a trait and it gives an alias to a namespace. Require_once used to embed PHP code from another file. Here we embeds three files of PHPMailer.
  16. ‘$mail’ refers new PHPMailer object. Variable ‘$alert’ initialized with null. If(isset($_POST['submit'])) is checking whether submit is set or not by ‘if’ condition. If yes means it stores user inputs of name, mail, message by post method to respective variables.
  17. Within try block SMTP server details are collected those are pointed by ‘$mail’. Here we need to edit username, password, setFrom and addAddress by using our SMTP gmail account details.
  18. If the mail sent successfully success alert message will show on display or catch block throws the error.
  19. Notes: we need server, internet and in our gmail account turn on the ‘less secure’ option for achieve successful result.
  20. Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.

Conclusion :-

In conclusion now we are learn using PHPMailer we can send html form data to email and also stored to database.

When we using database we can maintain so many records of information and we can modify, retrieve or delete like anything we can do on database.

In PHPMailer package we can study more concepts and simplified to use depends on our need. Today’s all website needs email facilities so we have to know how to handle.

Most of dynamic websites had type of process to sends like with attachments, with form details, with popups or documents(doc,xl,ppt).

So, I hope this tutorial on PHP submit form to database and email helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪