I am trying to send a form that it has taken me about 3 days to manage to build! I am really struggling with php but learning. Anyway, I have done what I think is correct but my form is not getting to me? I hope this is an easy fix! Code is as follows and I really appreciate any help:
<?php
// define variables and set to empty values
$addDateErr = $nameErr = $emailErr = $subjectErr = $messageErr = $questionErr = "";
$addDate = $name = $email = $subject = $message = $WebSearch = $SocialMedia = $WordOfMouth = $Other ="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Date
if (empty($_POST["addDate"]))
{$comment = "";}
else
{$comment = test_input($_POST["addDate"]);}
//Name
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
//Email
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
//Subject
if (empty($_POST["subject"]))
{$comment = "";}
else
{$comment = test_input($_POST["subject"]);}
//Message
if (empty($_POST["message"]))
{$messageErr = "A message is required";}
else
{$comment = test_input($_POST["message"]);}
//Question
if (isset($_POST['question']))
{
$menuVar = $_POST['question'];
} else {
$menuVar = "----------";}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" id="form" action="send.php">
<p><span class="error">* required field.</span></p><br />
<!--<form method="post" id="form" action="<php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">-->
<!--Date--><div class="contact-font">
Date Photography needed (if necessary)<br />
<input type="text" name="addDate" id="datepicker" size="25" value="<?php if(isset($_POST['addDate'])) {echo $_POST['addDate']; } ?>">
</div>
<!--Name--><div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Name:<br />
<input type="text" name="name" class="border" size="25" value="<?php if(isset($_POST['name'])) {echo $_POST['name']; } ?>">
<span class="error"><?php echo $nameErr;?></span>
</div>
<!--Email--><div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Email: (please double check enty)<br />
<input type="text" name="email" class="border" size="25" value="<?php if(isset($_POST['email'])) {echo $_POST['email']; } ?>"><span class="error">
<?php echo $emailErr;?></span>
</div>
<!--Subject--><div class="contact-font" style=" margin-top: 20px;">
Subject:<br />
<input type="text" name="subject" class="border" size="25" value="<?php if(isset($_POST['subject'])) {echo $_POST['subject']; } ?>">
</div>
<!--Message--><div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Message:<br />
<textarea cols="40" rows="10" name="message" class="border"><?php if(isset($_POST['message'])) {echo $_POST['message']; } ?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div><br />
<select name="question">
<option <?php if($menuVar=="----------") echo 'selected="selected"'; ?> value="----------">----------</option>
<option <?php if($menuVar=="WebSearch") echo 'selected="selected"'; ?> value="WebSearch">Web Search</option>
<option <?php if($menuVar=="SocialMedia") echo 'selected="selected"'; ?> value="SocialMedia">Social Media</option>
<option <?php if($menuVar=="Wordofmouth") echo 'selected="selected"'; ?> value="Wordofmouth">Word of mouth</option>
<option <?php if($menuVar=="Other") echo 'selected="selected"'; ?> value="Other">Other</option>
</select>
<div>
<input type="submit" value="Send" id="submit">
</div>
</form>
<script>
$(document).ready(function() {
$("#datepicker").datepicker({minDate: 129, maxDate: "+5Y", changeMonth: true,changeYear: true, showButtonPanel: true, dateFormat: 'dd MM yy'});
});
$('#form').on('submit', function(){
return $('#email').val() == $('#emailConfirmation').val();
});
</script>
<style type="text/css">
.asterix{color: #bc2021;font-size: 20px;}
.contact-font, #info-req, #opening-text{font-family: 'Raleway', sans-serif; font-weight: 100; color: #000;}
.border:focus{border: 2px solid #bc2021;}
#datepicker:focus{border: 2px solid #bc2021;}
.error {color: #FF0000;}
#marketing{border: 1px solid black; width: 150px; height: 22px;}
#submit{width: 100px; height: 25px; font-size: 15px;}
#submit:active{background-color: #bc2021;}
</style>
Below is the send.php file contents:
<?php
$addDate = $_POST['addDate'];
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$question = $_POST['question'];
$to = "some#email.com";
$subject = "Help!";
$body = "Please do not reply!";
mail($to,$subject,$body);
echo "Message Sent!<a href='index.html'>Home</a>";
?>
Related
I have moved over the validation to the bikeInfo.php file. Not much changes have been made to the code, but not sure why the validation is not being processed... appreciate the help!
<?php
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = "";
$name = $phone = $email = $serial = $type = $formSubmit = $description = "";
?>
<head>
<title>Register your bikes!</title>
</head>
<style>
body {
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 8px;
}
div.sellerInfo {
position: relative;
top: 50px;
}
.error {
position: absolute;
color: red;
}
</style>
<html>
<body>
<form method="post" action="bikeInfo.php">
<b style="font-size: 20px;">Bike Information</b>
</br></br>
<div class="sellerInfo">
Name:
<input type="text" name="sName" value="<?php echo $name;?>"/>
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Phone:
<input type="text" name="sNum" value="<?php echo $phone;?>"/>
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Email:
<input type="text" name="sEmail" value="<?php echo $email;?>"/>
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Serial:
<input type="text" placeholder="yy-nnn-cc" name="serial" value="<?php echo $serial;?>"/>
<span class="error">* <?php echo $sErr;?></span>
<br><br>
Type:
<input type="text" name="type" value="<?php echo $type;?>"/>
<span class="error">* <?php echo $errorMsg;?></span>
<br><br>
Description:
<textarea name="description" rows="5" cols="50" value="<?php echo $description;?>"></textarea>
<br><br>
<input type="submit" name="formSubmit" value="Submit"/>
</div><br><br><br>
</form>
</body>
</html>
This is my bikeInfo.php file which does validation and displaying of the submitted values. Not sure am i suppose to separate them...
<?php
//set to empty strings
$name = $phone = $email = $serial = $type = $formSubmit = $description = "";
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = "";
if (isset($_POST["formSubmit"]))
{
if (empty($_POST["sName"]))
{
$nameErr = "Name is required";
} else {
$name = test_input($_POST['sName']);
}
//validate phone number
if (empty($_POST["sNum"]))
{
$phoneErr = "Phone number is required";
} else {
$phone = test_input($_POST['sNum']);
if (!is_numeric($phone)) //check for letters
{
$phoneErr = "No letters allowed";
}
}
//validate email
if (empty($_POST["sEmail"]))
{
$emailErr = "Email is required";
} else {
$email = test_input($_POST['sEmail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}
//validate serial
if (empty($_POST["serial"]))
{
$sErr = "Serial number is required";
} else {
$serial = test_input($_POST['serial']);
//determing the pattern of the serial no. yy-nnnn-cc
if (!preg_match("/[0-9][0-9]\-\d{3}\-[a-z]{2}/", $serial))
{
$sErr = "Format is yy-nnn-cc";
}
}
//validate type
if (empty($_POST["type"]))
{
$errorMsg = "Type is required";
} else {
$type = test_input($_POST["type"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<style>
.body {
text-align: center;
padding: 20px;
}
</style>
<body>
<h1 style="text-align:center; padding: 20px">Bike listings</h1>
<?php
$listings = $name . "<br>" . $phone . "<br>" . $email . "<br>" . $serial . "<br>" . $type . "<br>" . $description;
echo "<div style='text-align:center; padding: 50px'>$listings</div>";
?>
</body>
</html>
I had a little play about refactoring the code so that you could use a single page to perform both the validation and display. Perhaps it may be of use.
<?php
error_reporting( E_ALL );
$errors=array();
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = '';
$sName = $sNum = $sEmail = $serial = $type = $description = '';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['sName'],
$_POST['sNum'],
$_POST['sEmail'],
$_POST['serial'],
$_POST['type']
)){
# modified to accept uppercase chars at end and limited to 2 integers at atart
$pttn='/[0-9]{2}\-\d{3}\-[a-zA-Z]{2}/';
# config to filter POST vars
$args=array(
'sName' => FILTER_SANITIZE_STRING,
'sNum' => FILTER_SANITIZE_STRING,
'sEmail' => FILTER_SANITIZE_EMAIL,
'serial' => FILTER_SANITIZE_STRING,
'type' => FILTER_SANITIZE_STRING,
'description' => FILTER_SANITIZE_STRING
);
# test for unaccounted POST fields - possibly malicious
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) ){
$errors[]=sprintf('Unknown field %s',$field);
}
}
if( empty( $errors ) ){
# rebuild the POST array with only filtered values
$_POST=filter_input_array( INPUT_POST, $args );
# extract known values from POST array into variables
extract( $_POST );
#error messages
$nameErr=empty( $sName ) ? 'Name is required' : '';
$phoneErr=empty( $sNum ) ? 'Phone number is required' : '';
$emailErr=empty( $sEmail ) ? 'Email is required' : '';
$sErr=empty( $serial ) ? 'Serial number is required' : '';
$errorMsg=empty( $type ) ? 'Type is required' : '';
# Validate particular variables
$sEmail=filter_var( $sEmail, FILTER_VALIDATE_EMAIL );
# to filter the phone number might remove leading zero and thus appear invalid
# possibly reassign error message variables
if( !preg_match( $pttn, $serial ) )$sErr='Invalid Serial. The format is: yy-nnn-cc';
if( !$sEmail )$emailErr='Invalid email format';
if( !$sNum )$phoneErr='Invalid phone number. No letters allowed!';
# save to database, email somewhere, write text etc etc
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register your bikes!</title>
<style>
body {
margin:auto;
text-align:center;
padding:8px;
}
div.sellerInfo {
top:50px;
}
.error {
position:absolute;
color:red;
}
section{
margin:2rem auto;
width:300px;
padding:1rem;
display:block;
border:1px solid black;
}
section *{
text-align:left;
}
</style>
</head>
<body>
<form method='post'>
<b>Bike Information</b>
<div class='sellerInfo'>
<div>
Name:
<input type='text' name='sName' value='<?php echo $sName;?>' />
<span class='error'>* <?php echo $nameErr;?></span>
</div>
<div>
Phone:
<input type='text' name='sNum' value='<?php echo $sNum;?>' />
<span class='error'>* <?php echo $phoneErr;?></span>
</div>
<div>
Email:
<input type='text' name='sEmail' value='<?php echo $sEmail;?>' />
<span class='error'>* <?php echo $emailErr;?></span>
</div>
<div>
Serial:
<input type='text' placeholder='yy-nnn-cc' name='serial' value='<?php echo $serial;?>' />
<span class='error'>* <?php echo $sErr;?></span>
</div>
<div>
Type:
<input type='text' name='type' value='<?php echo $type;?>' />
<span class='error'>* <?php echo $errorMsg;?></span>
</div>
<div>
Description:
<textarea name='description' rows='5' cols='50' value='<?php echo $description;?>'></textarea>
</div>
<input type='submit' />
</div>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$sName,
$sNum,
$sEmail,
$serial,
$type,
$description
)){
if( empty( $errors ) ){
printf('
<section>
<h1 style="text-align:center; padding: 20px">Bike listings</h1>
<ul>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
</ul>
</section>',
$sName,
$sNum,
$sEmail,
$serial,
$type,
$description
);
}else{
foreach( $errors as $error )printf('<div class="error">%s</div>',$error);
}
}
?>
</body>
</html>
im creating a php registration form using ajax, the below code that i have pasted isnt seems to be working , im literially new to this ajax concept
when i click the register button it wont respond anything, and even in the database the values are not getting stored i have seached a lot for this ajax concept
but i don seem to get the result what i want please can any one help me where im actually going wrong please help me.
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color: #f2f2f2;">
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $ageErr = "" ;
$name = $email = $username = $password = $age = "";
if (isset($_POST['name'])) {
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";
}
}
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["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password))
{
$passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
}
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
}
elseif($_POST["age"]< 17 ) {
$ageErr = "Age should be above 18 years";
}
else {
$age = $_POST["age"];
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $ageErr == "")
{
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "copy" style="margin-left: 52px" value ="<?php
if (isset($name))
echo $name;
?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "copy" style="margin-left: 48px" value ="<?php
if (isset($email))
echo $email;
?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "copy" style="margin-left:26px" value ="<?php
if (isset($username))
echo $username;
?>">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "copy" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "copy" style="margin-left:62px" value ="<?php
if (isset($age))
echo $age;
?>">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
<input type="button" class="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
script.js
$(document).ready(function(){
$(".submit").click(function(){
var name = $("name").val();
var email = $("email").val();
var username = $("username").val();
var password = $("password").val();
var age = $("age").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
var dataString = $("form").serialize();
if(name==''|| email==''|| username==''|| password==''|| age=='')
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'ajax1';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
Update the submit button with submit class
<input type="button" class="submit" name="submit" value="submit">
Update the js code with . insted of # // as # is for id
$(".submit").click(function(){
Also, use the form serialize
var dataString = $("form").serialize();
Php code change the submit to name
if(isset($_POST['name']))
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
background-color: #f2f2f2;
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body>
<?php
session_start();
if (isset($_SESSION['id'])){
header('location:welcome.php');
}
?>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = $fileToUploadErr = $fileToUploadErrr = $fileToUploadErrrr = $fileToUploadErrrrr = $fileToUploadErrrrrr = "" ;
$name = $email = $username = $password = $DateOfBirth = $department = $age = $fileToUpload = $filename = $file = "";
if (isset($_POST['submit'])) {
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";
}
}
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["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password))
{
$passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
}
}
if (empty($_POST["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = test_input($_POST["Date_of_birth"]);
}
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = test_input($_POST["department"]);
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
}
//UPLOAD FILE
$uploaddir = 'upload/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
$imageFileType = pathinfo($uploadfile,PATHINFO_EXTENSION);
if($_FILES['fileToUpload']['name'] != '')
{
// Check the image is actaully image or not
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check == false)
{
$fileToUploadErrrrr = "File is not an image.";
}
// Check if file already exists
if (file_exists($uploadfile)) {
$fileToUploadErrrrrr = "Sorry, file already exists.";
}
if($imageFileType != "jpg" && $imageFileType != "png" )
{
$fileToUploadErr = "Sorry, only JPG,PNG files are allowed.";
}
elseif($_FILES['fileToUpload']['size'] > 500000)
{
$fileToUploadErrrr = "Sorry, your file is too large.";
}
else
{
/* if($filename != '')
{
$target = "upload/".$filename;
unlink($target);
}*/
$uploaded = move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile);
if ($uploaded) {
$file = $_FILES['fileToUpload']['name'];
}
else{
$file = $filename;
}
}
}
elseif($_FILES['fileToUpload']['name'] = " ")
{
$fileToUploadErrr = "Please Select an image!";
}
else {
$file = $filename;
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $fileToUploadErr == "" && $fileToUploadErrr == "" && $fileToUploadErrrr == "" && $fileToUploadErrrrr == "" && $fileToUploadErrrrrr == "" )
{
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `Date_of_birth` , `department` ,`age` , `filename` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."' , '".$file."')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "copy" style="margin-left: 52px" value ="<?php
if (isset($name))
echo $name;
?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "copy" style="margin-left: 48px" value ="<?php
if (isset($email))
echo $email;
?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "copy" style="margin-left:26px" value ="<?php
if (isset($username))
echo $username;
?>">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "copy" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
<span style="color:#0099ff"> Date Of Birth : </span>
<input type="date" class= "copy1" name="Date_of_birth" value ="<?php
if (isset($DateOfBirth))
echo $DateOfBirth;
?>">
<span class="error"> <?php echo $DateOfBirthErr;?></span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "copy" style="margin-left:62px" value ="<?php
if (isset($age))
echo $age;
?>">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
<span style="color:#0099ff"> Department : </span>
<select name="department" class= "copy2" style="margin-left:14px" value ="<?php
if (isset($department))
echo $department;
?>">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr;?></span>
<br><br>
<span style="color:#0099ff"> Select image : </span>
<input type="file" name="fileToUpload">
<?php if($filename !=''){ ?> <img src="<?php echo "upload/" .$filename ?>" style="width:180px;height:100px;padding:10px;"/> <?php } ?>
<span class="error"><br> <?php echo $fileToUploadErr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrrr; ?></span>
<input type="submit" class="button" name="submit" value="Register">
<p style="color:black">Already Registered? Login.</p>
</form>
</div>
</body>
</html>
Hi, guys I have only one small issue please help me, I have a registration form with the various input,
my problem is if I give blank space to the name input field and then if I give submit then it should
show any error that no space are allowed
i.e., their should be only letters except that it should not accept any numbers special characters and other thing please.
Can any one help me in this please ?
This line if (!preg_match("/^[a-zA-Z ]*$/",$name)) { must be like this:
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
Explanation:
Your regex has a space at the end. Removing it will solve your problem.
I'm recieving an issue in the following php code. I am recieiving an unknown variable error in line 146, (echo $newrecord) variable. I'm not sure what is wrong with this variable, I have defined it in the IF statement, and am simply echoing if it is successful. I originally had that segment of code (after ) at the top of the script, but it was causing issues with the mandatory field error messages displaying properly. Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
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["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required"; }
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
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>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
echo $sub;
?>
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO newspaper (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} // end of nested if statement
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
newrecord is defined and initialized inside the if statement, therefore if your code opts to the else, it will skip the if and your newrecord variable won't exist.
$newrecord is defined within an if statement, when the if is not executed the variable is not available. You can define it by default adding $newrecord = ''; before you start the if for the submit.
I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email 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 = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}