Submit goes to action page even without value - php

Every time I press submit. It goes straight to the (action) page without checking to see if any value is filled in.How do I stop it from changing pages without first checking to see if any information is filed in the name email and comment?
<?php
if( empty($name) && isset($_POST["submit"])){
global $connect;
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST["comment"];
$sql = "INSERT INTO entries (fullName,email,comment)
VALUES ('$name', '$email', '$comment')";
$result = mysqli_query($connect, $sql);
if(!$result){
die("try again" .mysqli_error());
}
}
?>
<section>
<div class="container text-center ">
<h1>Guess Book</h1>
<div class="row"></div>
<form class="text-center" action="thankYou.php" method="post" id="signUp" >
<label class="mb-2 mt-2" style="padding-right:1vh" for="name">Please Enter Your Full Name Here:</label><input type="text" name="name" placeholder="Enter Full Name" minlength="3" ><br>
<label class="mb-2 mt-2" style="padding-right:4.1vh" for="email">Please Enter Your Email Here:</label><input type="email" name="email" placeholder="Enter Email" minlength="4" ><br>
<div class="form-group ">
<label for="comment">Comment:</label>
<textarea name="comment" class="form-control mb-3" rows="8" minlength="4" id="comment"></textarea>
</div>
<input class="bottom-pad" type="submit" name="submit">
</form>
</div>
</section>

the simplest option is to use html "required" attribute
in your case:
<input type="text" name="name" placeholder="Enter Full Name" minlength="3" required>
this is client side validation, you also always need to validate server side.
your code:
if( empty($name) && isset($_POST["submit"])){
is slightly wrong, here is the fixed version
if( !empty($_POST['name']) && isset($_POST["submit"])){

The reason why it get submited , it because your not doing any validation in the form for a minimal validation you can use required on the input field
Please consider using a better validation i just used this for the purpose of demonstration
<section>
<div class="container text-center ">
<h1>Guess Book</h1>
<div class="row"></div>
<form class="text-center" action="thankYou.php" method="post" id="signUp" >
<label class="mb-2 mt-2" style="padding-right:1vh" for="name">Please Enter Your Full Name Here:</label><input type="text" name="name" placeholder="Enter Full Name" minlength="3" required><br>
<label class="mb-2 mt-2" style="padding-right:4.1vh" for="email">Please Enter Your Email Here:</label><input type="email" name="email" placeholder="Enter Email" minlength="4" required><br>
<div class="form-group ">
<label for="comment">Comment:</label>
<textarea name="comment" class="form-control mb-3" rows="8" minlength="4" id="comment" required></textarea>
</div>
<input class="bottom-pad" type="submit" name="submit">
</form>
</div>
</section>

You can do form validation like the previous answers have suggested. This will prevent the form from submitting unless the inputs that are required have a value in them.
You should also get in the habit of validating your code on the server side as well to make sure the data submitted by the user is the information you expect to be submitted by the user.
Here is some simple code to check to make sure that the values at least have something in them. You can take it further to validate that each field has data that meets certain criteria like a name only having alpha characters.
if($_POST["submit"] && isset($_POST["submit"])){
global $connect;
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST["comment"];
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["comment"])){
$sql = "INSERT INTO entries (fullName,email,comment)
VALUES ('$name', '$email', '$comment')";
$result = mysqli_query($connect, $sql);
if(!$result){
die("try again" .mysqli_error());
}
} else {
echo 'You must enter enter a value for all fields.';
}
}

Related

PHP - Problem on validating empty form field

I have a simple form that contains three inputs: name, message and email.
On the server side, I validate all these fields, however, I'm strugling to validate the name field. If I leave the input blank or start writing with a space (single, double, or more) and hit on submit, my php code is accepting this name as valid (where it should not).
Does someone knows how to prevent this? 
Heres my code:
Page 1 - the form:
<form action="enviar-email.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" class="form-control" id="name" name="nome" placeholder="Type your name here" >
</div>
<div class="form-group">
< input type="text" class="form-control" id="email" name="email" placeholder="Youre#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="write your message" ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send" class="btn btn btn-special" onclick="alert('Thanks!')" >
</div>
</form>
Page 2 - PHP page where I validate the fields.
if(isset($_POST['nome'])){ $nome = $_POST['nome']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['mensagem'])){ $message = $_POST['mensagem']; }
// blank fields or name that start with space are not getting caught by this if
if(isset($nome) && trim($nome) !== ""){
Header("location:contato.php");
}
if (!preg_match("/^[a-zA-Z ]+$/",$nome)) {
Header("location:contato.php");
}
you can try like this -
if(isset($_POST['name']) && !empty($_POST['name'])){ $name = $_POST['name']; }

User register is successful, however the data is not stored in database without showing any error

Sorry if what I'm going to ask is a dumb question, but I have read through and even apply some of the solutions to my problem but it's still not working. I've got the solutions from here:
1. Not Getting response after registration is successful
2. php register form not updating database
3. Inserted data was not saved during registration
I have a system where the user can register himself/herself as a candidate for job interviews. But right now, the system doesn't save their registration. I have go through the queries but find nothing. Perhaps anybody can point out where I have been doing wrong that make my system doesn't want to keep the data.
my register-candidates.php
<section class="content-header">
<div class="container">
<div class="row latest-job margin-top-50 margin-bottom-20 bg-white">
<h1 class="text-center margin-bottom-20">CREATE YOUR PROFILE</h1>
<form method="post" id="registerCandidates" action="adduser.php" enctype="multipart/form-data">
<div class="col-md-6 latest-job ">
<div class="form-group">
<input class="form-control input-lg" type="text" id="fname" name="fname" placeholder="First Name *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="lname" name="lname" placeholder="Last Name *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="email" name="email" placeholder="Email *" required>
</div>
<div class="form-group">
<textarea class="form-control input-lg" rows="4" id="aboutme" name="aboutme" placeholder="Brief intro about yourself *" required></textarea>
</div>
<div class="form-group">
<label>Date Of Birth</label>
<input class="form-control input-lg" type="date" id="dob" min="1960-01-01" max="1999-01-31" name="dob" placeholder="Date Of Birth">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="age" name="age" placeholder="Age" readonly>
</div>
<div class="form-group">
<label>Passing Year</label>
<input class="form-control input-lg" type="date" id="passingyear" name="passingyear" placeholder="Passing Year">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="qualification" name="qualification" placeholder="Highest Qualification">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="stream" name="stream" placeholder="Stream">
</div>
<div class="form-group checkbox">
<label><input type="checkbox"> I accept terms & conditions</label>
</div>
<div class="form-group">
<button class="btn btn-flat btn-success">Register</button>
</div>
<?php
//If User already registered with this email then show error message.
if(isset($_SESSION['registerError'])) {
?>
<div class="form-group">
<label style="color: red;">Email Already Exists! Choose A Different Email!</label>
</div>
<?php
unset($_SESSION['registerError']); }
?>
<?php if(isset($_SESSION['uploadError'])) { ?>
<div class="form-group">
<label style="color: red;"><?php echo $_SESSION['uploadError']; ?></label>
</div>
<?php unset($_SESSION['uploadError']); } ?>
</div>
<div class="col-md-6 latest-job ">
<div class="form-group">
<input class="form-control input-lg" type="password" id="password" name="password" placeholder="Password *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="password" id="cpassword" name="cpassword" placeholder="Confirm Password *" required>
</div>
<div id="passwordError" class="btn btn-flat btn-danger hide-me" >
Password Mismatch!!
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="contactno" name="contactno" minlength="10" maxlength="10" onkeypress="return validatePhone(event);" placeholder="Phone Number">
</div>
<div class="form-group">
<textarea class="form-control input-lg" rows="4" id="address" name="address" placeholder="Address"></textarea>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="city" name="city" placeholder="City">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="state" name="state" placeholder="State">
</div>
<div class="form-group">
<textarea class="form-control input-lg" rows="4" id="skills" name="skills" placeholder="Enter Skills"></textarea>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="designation" name="designation" placeholder="Designation">
</div>
<div class="form-group">
<label style="color: red;">File Format PDF Only!</label>
<input type="file" name="resume" class="btn btn-flat btn-danger" required>
</div>
</div>
</form>
</div>
</div>
</section>
adduser.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$firstname = mysqli_real_escape_string($conn, $_POST['fname']);
$lastname = mysqli_real_escape_string($conn, $_POST['lname']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$city = mysqli_real_escape_string($conn, $_POST ['city']);
$state = mysqli_real_escape_string($conn, $_POST ['state']);
$contactno = mysqli_real_escape_string($conn, $_POST ['contactno']);
$qualification = mysqli_real_escape_string($conn, $_POST ['qualification']);
$stream = mysqli_real_escape_string ($conn, $_POST['stream']);
$passingyear = mysqli_real_escape_string($conn, $_POST['passingyear']);
$dob = mysqli_real_escape_string($conn, $_POST['dob']);
$age = mysqli_real_escape_string($conn, $_POST['age']);
$designation = mysqli_real_escape_string($conn, $_POST['designation']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$skills = mysqli_real_escape_string($conn, $_POST['skills']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
//Folder where you want to save your image. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/resume/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['resume']['name']);
//This will get us extension of your file. So myimage.pdf will return pdf. If it was image.doc then this will return doc.
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $resumeFileType;
//This is where your files will be saved so in this case it will be uploads/image/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['resume']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($resumeFileType == "pdf") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB ";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
//sql new registration insert query
$sql = "INSERT INTO users(firstname, lastname, email, password, address, city, state, contactno, qualification, stream, passingyear, dob, age, designation, resume, hash, aboutme, skills) VALUES ('$firstname', '$lastname', '$email', '$password', '$address', '$city', '$state', '$contactno', '$qualification', '$stream', '$passingyear', '$dob', '$age', '$designation', '$file', '$hash', '$aboutme', '$skills')";
if($conn->query($sql)===TRUE) {
//If data inserted successfully then Set some session variables for easy reference and redirect to company login
$_SESSION['registerCompleted'] = true;
header("Location: login-candidates.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: register-candidates.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: register-candidates.php");
exit();
}
thank you for the help and your time.
I think you should to debug your app by following those steps :
Try to direct insert data from SQL command in your ManagementInterface
Try to echo $var | var_dump($var) of each input you get from your form when you reach your register.php.
Try to see if you reach your condition like if(isset($_POST["var"]&&!empty($_POST["var"])) but if you can echo them it's not here you have to search
It might be your queries statement that block you.
You should try to improve your code with prepared statement for your SQL queries, it will be more readable and maintenable. Also, i think that mysqli & co are deprecated.
I hope it will be usefull for you and it ill help you to find your error.
Respond in comment if this doesn't help you, 'ill try to find out why
Regards
You have not defined $resumeFileType and in order for your script to execute, it has to check that the $resumeFileType is a PDF.

Contact form with reCaptcha [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I know this may have been submitted before (sorry)
I have basic form, these are the details id like to be sent, however i cannot get the reCaptcha to work with it. I have googled all day, but when i try other peoples code (amending to fit mine) it doesnt seem to work.
I would like: Name, Email, Number, newsletter (yes/no) and recaptcha to be sent/work.
Can someone please give me an idea where i may be going wrong? what i may need to add?
Thanks in advance!
Here is my Form (html)
<form method="POST" action="Form_Activation.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name" value="" required/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" value="" placeholder="you#example.com" required/>
</div>
<div class="form-group">
<label for="number">Number:</label>
<input class="form-control" name="number" id="number" value="" placeholder="Contact Number" required/>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" name="message" id="message" placeholder="Enter Message.." required></textarea>
</div>
<div class="form-group">
<input type="checkbox"/> <b> Subscribe to Newsletter</b>
</div>
<div class="g-recaptcha" data-sitekey="6Le2SBQTAAAAADIOrUEPpcEVvR_c0vN9GzQpLg05"></div>
<button type="submit" class="btn btn-default sendbutton">SEND</button>
</form>
Here is my php (basic)
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
//$password = $_POST['password'];
//$keyy = $_SERVER['UNIQUE_ID'];
$msg = "Name: $name\r\n \r\n";
$msg .= "Email: $email\r\n \r\n";
$msg .= "Number: $number\r\n \r\n";
$msg .= "Message: $message\r\n \r\n";
$recipient = "info#islandwebdesign.co.uk";
$subject = "New Website Request";
$mailheaders = "From:$email";
//$mailheaders .= "Reply-To:$email";
mail($recipient,$subject,$msg,$mailheaders);
header("Location: contactus.php?msg=1");
?>
First of all make sure that you've included the necessary JavaScript resource to render reCAPTCHA widget properly, like this:
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Here's the reference:
Displaying the widget
Now comes to your user's response. The response from the user's captcha challenge can be fetched in three ways. It can be as,
Now comes to your user's response. The response from the user's captcha challenge can be fetched in three ways. It can be as,
g-recaptcha-response - a POST parameter in the submitted form
grecaptcha.getResponse(widget_id) - will provide the response after the user completes the captcha.
A string argument to the callback function specified in the config object passed to the render method.
Here's the reference:
Verifying the user's response
For your purpose use g-recaptcha-response to get the user's response. So your code should be like this:
HTML
<form method="POST" action="Form_Activation.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name" value="" required/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" value="" placeholder="you#example.com" required/>
</div>
<div class="form-group">
<label for="number">Number:</label>
<input class="form-control" name="number" id="number" value="" placeholder="Contact Number" required/>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" name="message" id="message" placeholder="Enter Message.." required></textarea>
</div>
<div class="form-group">
<input type="checkbox"/> <b> Subscribe to Newsletter</b>
</div>
<div class="g-recaptcha" data-sitekey="6Le2SBQTAAAAADIOrUEPpcEVvR_c0vN9GzQpLg05"></div>
<button type="submit" name="submit" class="btn btn-default sendbutton">SEND</button>
</form>
Add a name attribute in your submit button.
Form_Activation.php
<?php
if(isset($_POST['submit'])){
//your site secret key
$secret = 'XXXXXXX_Secret-key_XXXXXXX';
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
// so on
}else{
// failure
}
}
}
?>
Don't forget to add your secret key in $secret variable.

PHP multi-step registration process

I am working on a registration system which comprises of 3 total steps.
Step 1 - user enters a username, system searches the database for the
username. IF the username is found, it checks the account status (ie:
no password created, complete but not verified, registered and
verified).
If user is not found, user is directed to Step 2.
If status = no password created, the user is directed to Step 3.
If status = complete but not verified / registered and verified, Display error message.
Step 2 - user enters personal details.
The page stores user inputs
Step 3 - user creates a password, the system connects to the database and INSERTs user info to the user table. A success message is
displayed.
I have managed to figure out and complete the coding for the first 2 steps, by displaying a new form when the previous form has been submitted.
Problem: However, I have just realised that I am unable to retrieve data from the previous form (ie: at step 3 I am unable to retrieve the Username from Step 1). I have tried using the 'header('location: ?user=$uname');' approach however this doest work because the URL gets reset when I submit the new form and I lose the username again. How do I create a proper multi-step form using ONLY PHP and how do I store the input values so I could use them at the last step. Below is my code:
<?php
include 'includes/session_info.php';
if(isset($_SESSION['user_id'])){
header('Location: index.php');
}
$errors = array();
if(empty($_POST['user_info']) === false){
require ('core/dbcon.php');
$usr_email = mysqli_real_escape_string($con, $_POST['email']);
$usr_joined = mysqli_real_escape_string($con, $_POST['joined']);
$usr_recruited = mysqli_real_escape_string($con, $_POST['recruited']);
if($usr_email){
//direct user to password form
}else{
$errors[] = 'Please complete all fields marked with a Red Asterisk.';
}
$form2 = $usr_email.'<br>'.$usr_joined.'<br>'.$usr_recruited;
}
if(empty($_POST['username_chck']) === false){
require ('core/dbcon.php');
$username = mysqli_real_escape_string($con, $_POST['uname']);
$rpt_uname = mysqli_real_escape_string($con, $_POST['r_uname']);
if($username && $rpt_uname){
if($username == $rpt_uname){
$query = mysqli_query($con, "SELECT status FROM users WHERE username = '$username'") or die(mysqli_error($con));
// Display registration form if Username is not found.
if(mysqli_num_rows($query) == 0){
$form1;
}
// Actions performed If username entered already exists in the database.
elseif(mysqli_num_rows($query) == 1){
$status = mysqli_fetch_assoc($query);
if($status['status'] == 0){
$errors[] = '<b>'.$username.'</b> is already registered and awaiting to be verified by our admins. Feel free to contact an Admin via the website or in-game to get verified.';
}elseif($status['status'] == 1){
//header("Location:?create_pwd&user=$username");
}elseif($status['status'] > 1){
$errors[] = '<b>'.$username.'</b> is already registered and verified by our Admins. Please log in to access you account.
If you have forgotten your password you can rest your password <a class="navbar-link error_link" id="intext-link" href="login.php?fp"><b>here</b></a>.';
}
}elseif(mysqli_num_rows($query) > 1){
$errors[] = 'An error has occurred. Looks like a there is more than one member with that username. Please contact the Administrator for assistance.';
}
}else{
$errors[] = 'Please ensure that the username entered in both fields match.';
}
}else{
$errors[] = 'Please complete all required fields.';
}
}
?>
<html>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<?php
if(empty($_POST['username_chck']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}else{ echo $reg_uname;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}
}elseif(empty($_POST['user_info']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}else
echo $reg_uname.'<br>'. $reg_email.'<br>'.$reg_joined.'<br>'.$reg_recruited.'<br>';
}else{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}
?>
</div>
</div>
</html>
Ps. I have looked into creating a session which gets destroyed when the user navigates away from the page Destroy PHP session on page leaving. However I find that it's not very user friendly as it doesn't work properly if the user has multiple tabs open. I understand that I need to implement a javascript function to make it work properly. I do not know how to code in javascript and would really appreciate your assistance on making a better multi-step registration process.
As mentioned above, store the POST data from each step in the session variable.
// Step 1 submit
$_SESSION['steps'][1] = $_POST;
// Step 2 submit
$_SESSION['steps'][2] = $_POST;
// Step 3 submit
$_SESSION['steps'][3] = $_POST;
You can then use something like currentStep in the session to determine where they last were.
$currentStep = $_POST['step'];
And compare to what data you need available, or just use it directly from the array.
I opted to follow the 'hidden variable' method where I store the values form the previous form in hidden inputs of the current form. Thus enabling me to pass the values on to the next form. A sort of snowball effect, if you will. Below is an example:
Form 1
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname">Username: </label><br>
<input type="text" name="uname" class="form-control" id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname">Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
Form 2
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email">Email: </label>
<input type="email" name="email" class="form-control" id="Email" required <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<input type="hidden" name="username" <?php if (isset($_POST['username'])=== true){echo 'value="', strip_tags($_POST['username']),'"';}else{echo "value=\"$username\"";}?>>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
Explanation
Below is a skeleton of my code which should help you understand how I have displayed the forms
if(empty($_POST['form1'])=== false){
$username = mysqli_real_escape_string($con, $_POST['username']);
// display form 2
}elseif(empty($_POST['form2'])=== false){
//display form 3
}
Note the hidden input type before the submit button in the second form.
While I have opted to include the if statements within the tags for the sake of this example, you could alternatively choose to process the forms at the top of your page (before the tag).

Populate database with data from a form

I want to fill all the fields in my database by getting the ones inputted on my form but it won't fill my database.
I don't know what's wrong with it:
<?php
$handle = mysql_connect("", "root" , "");
return mysql_select_db("bonggarden", $handle);
$SQL = "INSERT INTO table1(fname,femail,fphone,fmsg)
values('".$_POST['name']."','".$_POST['email']."','".$_POST['number']."','".$_PO ST['message']."')";
mysql_query($SQL);
?>
here is my form
<form id="main-contact-form" accept-charset="utf-8" class="" method="post" >
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" id="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" id="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone *</label>
<input type="text" name="number" id="number" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
<?php
$fname = $_POST['name'];
$femail = $_POST['email'];
$fphone = $_POST['number'];
$fmsg = $_POST['message'];
$handle = mysql_connect("localhost", "root" , "");
mysql_select_db("bonggarden", $handle);
$SQL = "INSERT INTO table1(fname,femail,fphone,fmsg) values('$fname','$femail','$fphone','$fmsg')";
mysql_query($SQL);
?>
// if it still not working echo the variable $fname, $femail, $fphone, $fmsg check value is proparly getting in veriable or not.
Try changing
return mysql_select_db("bonggarden", $handle);
to
mysql_select_db("bonggarden", $handle);
The return is exiting the code before you execute the insert...
You do not need the 'return' in:
return mysql_select_db("bonggarden", $handle);
You may also consider adding the location of your server to your 'mysql_connect' function. EX:
mysql_connect("localhost","root","");
A couple of suggestions too:
1.) Organizationally, assigning your values from $_POST to variables might make it easier to see what values you are sending to your database.
2.) Add a die function that outputs a MySQL error if your code cannot be run. This can often help with debugging and finding out the general location of your error. EX:
mysql_query($SQL) or die(mysql_error());
3.) Finally, and this gets said a lot on this website, consider switching to MySQLi as traditional 'mysql_' commands are now deprecated for security reasons.

Categories