I'm trying to input form data into the database. I'm using almost the same code as I did for my registration script, which works perfectly. I'm completely stumped at this point.
I have error reporting turned on for PHP and PDO, nothing is happening. When the form is sent, it appears to work (except without the confirmation messages appearing) but nothing is entered into the database.
I have two files, request.php (the form) and parseRequest.php (the backend to the form).
request.php
<form action="" method="post">
<div class="form-group">
<input type="hidden" class="form-control" name="username" id="usernameField" value="<?php echo $_SESSION['username'];?>">
</div>
<div class="form-group">
<label>Headlining Band/Artist</label>
<input type="text" class="form-control" name="artist" id="artistField" placeholder="Artist">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="day" id="dateField" placeholder="MM/DD/YYYY">
</div>
<div class="form-group">
<label>Venue</label>
<input type="text" class="form-control" name="venue" id="venueField" placeholder="Venue">
</div>
<div class="form-group">
<label>City, State</label>
<input type="text" class="form-control" name="city" id="cityField" placeholder="City, State">
</div>
<input type="hidden" name="token" value="<?php if(function_exists('_token')) echo _token(); ?>">
<button type="submit" name="requestBtn" class="btn btn-primary pull-right">Submit</button>
parseRequest.php
<?php
include_once 'resource/Database.php';
include_once 'resource/utilities.php';
include_once 'resource/send-email.php';
// Processing the form
if(isset($_POST['requestBtn'], $_POST['token'])){
if(validate_token($_POST['token'])) {
//process form here
$form_errors = "";
// validation
$required_fields = array('artist', 'day', 'venue', 'city');
// check empty fieldset
$form_errors = check_empty_fields($required_fields);
// date check
$fields_to_check_length = array('day' => 10);
//call the function to check minimum required length and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// collect data
$username = $_POST['username'];
$artist = $_POST['artist'];
$day = $_POST['day'];
$venue = $_POST['venue'];
$city = $_POST['city'];
}
else if(empty($form_errors))
{
// preparing and inputting data
try
{
$sqlInsert = "INSERT INTO requests(username, artist, day, venue, city)
VALUES (:username, :artist, :day, :venue, :city)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':username' => $username, ':artist' => $artist, ':day' => $day, ':venue' => $venue, ':city' => $city));
// email confirmation
$addresses = array($_SESSION['email'], 'codylkaczynski#gmail.com');
//prepare email body
$mail_body = '<html>
<body style="font-family: Arial, Helvetica, sans-serif;
line-height:1.8em;">
<h2>Amped Sound Staff Portal: Request Received</h2>
<p>Dear '.$username.'<br><br>
Your request for the '.$artist.' show in '.$city.' on '.$date.' has been received!</p><br/>
<p>We will let you know if your request has been approved or denied ASAP.</p><br/>
<p>Thank you!</p><br/>
<p><strong>©2018 Amped Sound</strong></p>
</body>
</html>';
$namejeff = explode(',', $addresses);
foreach ($addresses as $address)
{
$mail->AddAddress($address);
$mail->Subject = "Request Received!";
$mail->Body = $mail_body;
}
//Error Handling for PHPMailer
if(!$mail->Send())
{
$result = "<script type=\"text/javascript\">swal(\"Error\",\" Email sending failed: $mail->ErrorInfo \",\"error\");</script>";
}
else
{
$result = "<script type=\"text/javascript\">
swal({
title: \"Request received!\",
text: \"We have received your request! Please check your email for confirmation.\",
type: 'success',
confirmButtonText: \"Thank You!\" });
</script>";
}
}
catch (PDOException $ex)
{
$result = flashMessage("An error occurred: " .$ex->getMessage());
}
}
}
I appreciate any help I can get. I've tried a bunch of solutions I found on StackOverflow already, to no avail.
Related
I have created a form with HTML/PHP/SQL where a user can either choose to submit their email into a database or else select a radio button to opt out of their email being submitted, alongside some other user data.
To achieve this, I have written an if/else statement, however my current code isn't working, and I can't quite work out the correct syntax that I should be using. If the user selects the radio-button, I would like "Email unavailable" to be inserted into the database, else the user-inputted email is inserted. All help appreciated!
Note, my code worked fine until I added the radio-button "no email" option.
HTML file:
<form id="newStaff" method="POST" action="staffportal.php" enctype="multipart/form-data">
<b><i class="fas fa-user-alt"></i> Full name:</b>
<input class="form-control" type="text" id="staffName" name="myStaffName" size="40" maxlength="50"/>
//THE RELEVANT CODE
<b><i class="fas fa-paper-plane"></i> Email:</b>
<div class="form-group row">
<div class="col-xs-4">
<input class="form-control" type="text" id="staffEmail" name="myStaffEmail" size="40"/>
<br>
<input class="form-check-input" type="radio" name="myStaffNoEmail" id="staffNoEmail" value="option1">
<label class="form-check-label" for="gridRadios1">
No available email
</label>
</div>
</div>
<hr>
<b>Job title(s):</b>
<input class="form-control" type="text" id="staffJob" name="myStaffJob" size="40" maxlength="60"/>
<b>Personal bio:</b>
<textarea class="form-control summernote" rows='6' cols='70' id="staffBio" name="myStaffBio" maxlength='1500'></textarea>
<b>Profile photo:</b>
<input type="file" class="custom-file-input" name="myStaffPhoto" id="staffPhoto">
<button name="newStaffBtn" id="newStaffButton" onclick="return confirm('Create new profile?');" type="submit" class="btn btn-primary">Create Profile></button>
</form>
PHP file:
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
$staffNoEmail = mysqli_real_escape_string($conn, $_POST["myStaffNoEmail"]);
//Staff email option
if (!empty($staffNoEmail)){
$staffEmail = "Email unavailable";
} else {
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
If radio input is checked, it will send value with post, if it is not checked it will not send any value and it will not exist in your $_POST array.In your case, you should be checking if it is set.
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
//Staff email option
if (isset($_POST["myStaffNoEmail"])){
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
} else {
$staffEmail = "Email unavailable";
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
I am fairly new to PHP and a new student and so I will ask in advance to please forgive me if I have made errors that will be clearly obvious to someone experienced.
I am working on a page submission form that connects to a mysql database to either check for an existing value and if it does not exist then logs a string value of the datetime picker and also appends an id number to make a unique value to a table whenever someone was to press submit, and after form validation is accepted. Submitting if the record does not exist works and is ok.
However, whenever a record already exists, rather than displaying in the error message that the time is unavailable, the entire page just goes blank.
Initially, I had a button that would check to see if the record existed in the mysql table but I then decided it would be more efficient to try to include the date validation check of mysql table while completing the form validation and this is where I have trouble and of course the page breaks and nothing is displayed.
If someone could please guide me I would be most grateful.
it seems I am unable to add more code, but I will add what was wrong.
I did need to initialize $error=''; also $DateTime, and $id at the top of the script, I had it below but had forgotten to place it above and that was causing my problem.
<?php
$userid = "1";
$strid = strval($id);
$DateTimeCheck = $DateTime . $strid;
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->exec("SET CHARACTER SET utf8");
$sql = "SELECT booked FROM user_booking WHERE `booked` = :booked";
$sqlprep = $con->prepare($sql);
$ar_val = array(':booked' => $DateTimeCheck);
if (isset($_POST['datetime'])){
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
if (!$_POST['email']) {
$error .= "<br/>- Please enter your email";
}
if (!$_POST['message']) {
$error .= "<br/>- Please enter a message";
}
if (!$_POST['check']) {
$error .= "<br/>- Please confirm you are human";
}
if ($sqlprep->execute($ar_val)) {
while ($row = $sqlprep->fetch(PDO::FETCH_OBJ)) {
$DateTimeExists = $row->booked;
}
}
if (isset($DateTimeExists) && $DateTimeExists != ''){
$error .= "<br/>- The time you have requested is unavailable";
}
if ($error) {
$result = '<div class="alert alert-danger" role="alert"><strong>Whoops, there is an error</strong>. Please correct the following: ' . $error . '</div>';
} else {
mail("#gmail.com", "Contact message", "Name: " . $_POST['name'] . "
Email: " . $_POST['email'] . "
When: " . $_POST['datetime'] . "
Message: " . $_POST['message']);
{
$result = '<div class="alert alert-success" role="alert">Thank you, someone will be in touch soon to confirm your appointment. </div>';
$id = "$userid";
$strid = strval($id);
$DateTime = $_POST['datetime'];
$DateTimeCheck = $DateTime . $strid;
$strid = strval($id);
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_booking ( user_id, booked ) VALUES ( :id, :booked )";
$q = $con->prepare($sql);
$q->execute(array(':booked' => $DateTime . $strid,
':id' => $id));
$con = null;
}
}
}
?>
Here is the markup for the form.
<form method="post" role="form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your name"
value="<?php echo $_POST['name']; ?>">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your email"
value="<?php echo $_POST['email']; ?>">
</div>
<div class="form-group" align="left">
<label class="control-label">Date/Time</label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' name="datetime" class="form-control" placeholder="desired time"
value="<?php echo $_POST['datetime']; ?>">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<textarea name="message" rows="5" class="form-control"
placeholder="message..."><?php echo $_POST['message']; ?></textarea>
</div>
<div class="checkbox" align="left">
<label class="readable" align="left">
<input type="checkbox" name="check"> I am human
</label>
</div>
<div align="left">
<input type="submit" name="submit" class="btn btn-success" value="Book Appointment!"/>
</div>
</form>
If you are using .= you need to first initialise the variable before .= will work on the variable.
You attempted to do that in this IF block
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
but if that error is not present you will never actually initialise the $error variable.
So the simple solution is to initialise $error before getting into this section of code
$error = '';
if (isset($_POST['datetime'])){
// So now you can change this test to use .=
if (!$_POST['name']) {
$error .= "<br/>- Please enter your name";
}
Now the variable will be testable later in the code
If this is in fact the problem here, you should have been getting errors reported. If you didnt see any then try adding these lines of code to any problem script while you test it
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I created this signup page. The problem is when I click submit after I enter the information nothing happens. It just refreshes the same page. The info I enter should import into my database after I hit submit and display a thank you for signing up message after the submission. Please help. I'm trying to keep everything to single page by implementing the html and php code all on one page instead of 2 separate files.
<html>
<body>
<?php
$output_form = true; //declare a FLAG we can use to test whether or not to show form
$first_name = NULL;
$last_name = NULL;
$email = NULL;
if (isset($_POST['submit']) ) { //conditional processing based on whether or not the user has submitted.
$dbc = mysqli_connect('localhost', 'name', 'pswd', 'database')
or die('Error connecting to MySQL server.');
$first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$output_form = false; // will only change to TRUE based on validation
//Validate all form fields
if (empty($first_name)) {
echo "WAIT - The First Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($last_name)) {
echo "WAIT - The Last Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($email)) {
echo "WAIT - The Email field is blank <br />";
$output_form = true; // will print form.
}
if ((!empty($first_name)) && (!empty($last_name)) && (!empty($email))) {
//End of form validation
//This section establishes a connection to the mysqli database, and if it fails display error message
$query = "INSERT INTO quotes (first_name, last_name, email, " .
"VALUES ('$first_name', '$last_name', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
$to = 'email#email.com';
$subject = 'New Customer';
$msg = "$first_name $last_name\n" .
"Email: $email\n";
$mail = mail($to, $subject, $msg, 'From:' . $email);
if($mail){
header("Location: https://www.locate.com/blue.php".$first_name);
exit();
}
//Display the user input in an confirmation page
echo "<body style='margin-top: 100px; background-color: #f2f0e6;'><p style = 'color: #000000; text-align: center;font-size:300%; font-family:Arial, Helvetica, sans-serif;'><strong>Thanks for signing up!</strong></p><center><p style = 'color: #000000; text-align: center;font-size:200%; font-family:Arial, Helvetica, sans-serif;'>Contact us for any questions
</p>
</center>
</body>";
}//end of validated data and adding recored to databse. Closes the code to send the form.
} //end of isset condition. This closes the isset and tells us if the form was submitted.
else { //if the form has never been submitted, then show it anyway
$output_form = true;
}
if ( $output_form ) { //we will only show the form if the user has error OR not submitted.
?>
<div id="box">
<center><img src="../../images/duck.jpg" class="sign-up" alt="Sign Up"></center>
<br>
<p>Sign Up to get Discount Code</p><br>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<div>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" size="37" maxlength="37" value=" <?php echo $first_name; ?>" />
</div>
<div>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" size="37" maxlength="37" value="<?php echo $last_name; ?>" />
</div>
<div>
<label for="email">Email:</label>
<input type="text" id="email" name="email" size="37" maxlength="37" value="<?php echo $email; ?>" />
</div>
<div id="submit">
<input type="submit" name="Submit" value="Submit" />
</div>
</center>
</form>
</div>
<?php
}
?>
</body>
You are asking for $_POST['submit'] instead of $_POST['Submit']
I am working on a code right now that allows for the user to input their email and another user's email to add them as a "friend" into the table "friends"
So far my code works in terms of posting the form data into the DB / table "friends" however the message I would like to appear is not showing up at all.
My HTML form:
<form class="form-signin" action="FriendLookup.php" method = "POST" enctype="multipart/form-data">
<h2 class="form-signin-heading">Add a Friend</h2>
</br>
<label for="inputEmail" class="sr-only">Your Email</label>
<input type="text" id="inputEmail1" name = "self_email" class="form-control" placeholder="Friend's Username" >
</br>
<label class="sr-only">Your Friend's Email</label>
<input type="text" id="inputEmail2" name = "friend_email" class="form-control" placeholder="Your Username" >
</br>
<button class="btn btn-lg btn-primary btn-block" name = "submit" type="submit">Search</button>
</form>
PHP script:
<?php
include_once('support.php');
//connect_database.php contains your connection/creation of a PDO to connect to your MYSQL db on bmgt406.rhsmith.umd.edu/phpmyadmin
include_once('connect_database.php');
ini_set("display_errors","1");
error_reporting(E_ALL);
// Initialize $title and $body.
$title = "Add User";
$body = "<fieldset><legend> $title </legend>";
$name_of_table = "friends";
// Check if the table exists in the db.
if (tableExists($db, $name_of_table)) {
$inputemail1 = $_POST['self_email'];
$inputemail2 = $_POST['friend_email'];
// Prepare a SQL query and bind all 6 variables.
$sqlQuery = "INSERT INTO $name_of_table ( self_email, friend_email)
VALUES ( :self_email, :friend_email)";
$statement1 = $db->prepare($sqlQuery);
$statement1->bindValue(':self_email', $inputemail1, PDO::PARAM_STR);
$statement1->bindValue(':friend_email', $inputemail2, PDO::PARAM_STR);
// Execute the SQL query using $statement1->execute(); and assign the value
// that is returned to $result.
$result = $statement1->execute();
if(!$result) {
// Query fails.
$body .= "Inserting entry for friend failed.";
} else {
// Query is successful.
$body .= "Success";
}
// Closing query connection
$statement1->closeCursor();
}
$body .= "</fieldset>";
echo generatePage($title,$body);
?>
Any help is greatly appreciated. I am a novice programmer.
My function generatePage was wrong. I added HTML into the function and now it works!
I want to create a submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX. I've tried W3C schools and a couple of step by step guides but still struggling. So far, I've written the HTML for and Validation and connected to my SQL database. However, I'm not sure what steps to take next. I'm new to coding and not sure what to do next...
<?php
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = "";
$name = $email = $phone = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Telephone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["register.php"])?>">
<fieldset>
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Phone: <input type="tel" name="phone" value="<?php echo $phone;?>">
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
<button type="submit"> Submit</button>
</fieldset>
</form>
</div>
I will do it simply like this:
Create an empty div before Form's fieldset:
<div class="col-xs-12 col-sm-9 col-md-8 col-lg-8 conForm">
<h4>Shoot a message!</h4>
**<div id="message"></div>**
<form method="post" action="php/contact.php" name="cform" id="cform">
<input name="name" id="name" type="text" class="col-xs-12 col-sm-6 col-md-6 col-lg-6" placeholder="Your name..." >
<input name="email" id="email" type="email" class=" col-xs-12 col-sm-6 col-md-6 col-lg-6 noMarr" placeholder="Your email..." >
<textarea name="comments" id="comments" cols="" rows="" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your message..."></textarea>
<input type="submit" id="submit" name="submit" class="submitBnt" value="Send message">
<div id="simple-msg"></div>
</form>
</div>
in PHP print message like this after email sent:
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
As you asked, i think you are totally new in coding world.so that's why i write full code in one page. create a .php file and paste this code
<html>
<head>
<script type="text/javascript">
function validateName() {
var name = document.getElementById('contact-name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false; }
if (!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
producePrompt('First and last name, please.','name-error', 'red');
return false; }
producePrompt('Valid', 'name-error', 'green');
return true;}
function validatePhone() {
var phone = document.getElementById('contact-phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false; }
if(phone.length != 10) {
producePrompt('Include area code.', 'phone-error', 'red');
return false; }
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false; }
producePrompt('Valid', 'phone-error', 'green');
return true;}
function validateEmail () {
var email = document.getElementById('contact-email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false; }
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false; }
producePrompt('Valid', 'email-error', 'green');
return true;}
function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 10;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false; }
producePrompt('Valid', 'message-error', 'green');
return true;}
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false; } else { }
}
function jsShow(id) {
document.getElementById(id).style.display = 'block'; }
function jsHide(id) {
document.getElementById(id).style.display = 'none';}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;}
</script>
</head>
<form action="" method="POST">
<div class="form-group">
<label for="contact-name">Name</label>
<input type="text" class="form-control" id="contact-name" name="name" placeholder="Enter your name.." onkeyup='validateName()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="tel" class="form-control" id="contact-phone" name="phone" placeholder="Ex: 1231231234" onkeyup='validatePhone()'>
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contact-email" name="email" placeholder="Enter Email" onkeyup='validateEmail()'>
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" id='contact-message' name='message' placeholder="Enter a brief message" onkeyup='validateMessage()'></textarea>
<span class='error-message' id='message-error'></span>
</div>
<button onclick='return validateForm()' name="submit" value="submit" class="btn btn-default">Submit</button>
<span class='error-message' id='submit-error'></span>
<span class='success-message' id='submit-success'></span>
<?php
if (isset($_POST['submit']) && (!empty($_POST['submit']))) {
$servername = "localhost";
$username = "root"; //change this to your username
$password = ""; //change this to your database password
$dbname = "db"; //change this to your database name
$name = "$_POST[name]";
$phone = "$_POST[phone]";
$email = "$_POST[email]";
$message = "$_POST[message]";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);}
//insert data into table named guestbook
$sql = "INSERT INTO guestbook (name, email, phone, message) VALUES ('$name', '$email', '$phone', '$message')";
if ($conn->query($sql) === TRUE) {
echo "<br/><font color=green>Your Comment Successfully Sent</font>";
} else {
echo "Error updating record: " . $conn->error; }
$conn->close();}
?>
</form>
</body>
</html>
In your DATABASE, create a database whatever you named but dont forget to change in php file $dbname = ""; and create table with these code:
CREATE TABLE guestbook
(
id int NOT NULL AUTO_INCREMENT,
name varchar(255),
email varchar(255),
phone varchar(255),
message varchar(255),
PRIMARY KEY (id)
);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);
}
$sql = "INSERT INTO MyGuests (name, email, phonenumber,comment)
VALUES ($name , $email ,$phone,$comment)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: ".$sql."<br>".$conn->error;
}
$conn->close();
Where put you $comment , $name and others and also configure you database name, password and database table.