How to create a simple contact form in HTML and PHP
HTML Forms are one of the main points of interaction between a user and a web site.
I mostly use module for Drupal when needed web forms, but sometimes clients need something special. Things that normal web form can’t provide. This tutorial teaches how to create a simple web form, validate its data and send it as HTML e-mail. I also use email provided by the form as sender’s email so the client can press reply when contacting customer. You can also save all data to MySQL / MariaDB database if needed.
First, we need to create a form with basic text input fields and some radio box fields.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <input placeholder="name" type="text" name="name" maxlength="30" autofocus required> <input placeholder="email" type="text" name="email" maxlength=60 autocomplete=on required> <textarea name=comment rows=5 cols=40 value=message required></textarea> <ul> <li><input name="list2" type="radio" value="Value 1" /></li> <li><input name="list2" type="radio" value="Value 2" /></li> </ul> <input type="submit" value="Send" name="submit"> </form>
The name attribute is used to reference elements in PHP, or to reference form data after a form is submitted. The value attribute specifies the value that is sent to submit. The radio fields use the same name and those does not need foreach because only one selection can be active at a time.
Now that we have a form ready to use, we need to make PHP code which fetches submitted data from the field, process it and send an HTML email to whoever is the recipient of the message.
How to save all data from webform submissions to SQL database
You need to make a table with all rows you need to.
Put similar code after mail(). If you want a more secure method then make sql.php and put it somewhere where it's not accessible from the Internet and call it include('/somewhere/sql.php');.
<?php $servername = "Server IP"; $username = "Username"; $password = "Password"; $dbname = "Database"; $table = "Table"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) die("Connection failed: " . $conn->connect_error); $time = date("Y-m-d H:i"); $conn->query("INSERT INTO Form (Name, Email, Message, Up) VALUES ('$name', '$email', '$comment', '$time')"); $conn->close(); ?>