Am just getting my hand on php and I need some little help please. I am working on a registration form with server-side validation, then after validation, the form input should be submitted to the database. I entered data, click submit button, but the data were not submitted to the database. There is no error message. I like you to help me point out where have been wrong and give me a possible solution. Thanks.
Index.php
<?php
include ('signup.php');
?>
<div class="maindiv">
<div class="login"></div>
<div class="wrapper">
<div class="pageintro">
<p>PHP</p>
<p>PROJECT 1</p>
</div>
<div class="regform">
<form name="reg" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<p class="regformp">Fill all Fields</p>
<div class="regwrap">
<div class="inp">Full Name</div>
<div class="inp1"><input type="text" name="FullName" value="<?php echo $FullName; ?>"></div>
<span class="error"><?php echo $fullnameErr;?></span>
<div class="inp">E-Mail</div>
<div class="inp1"><input type="text" name="Email" value="<?php echo $Email; ?>"></div>
<span class="error"><?php echo $emailErr;?></span>
<div class="inp">Password</div>
<div class="inp1"><input type="password" name="Password"></div>
<span class="error"><?php echo $passwordErr;?></span>
<div class="inp">Confirm Password</div>
<div class="inp1"><input type="password" name="ConfirmPassword"></div>
<span class="error"><?php echo $conpasswordErr;?></span>
<div class="inp">Gender</div>
<div class="inp1"><input type="radio" name="Gender" value="Male" <?php if(isset($Gender)&& $Gender=="Male") echo "checked"; ?> >Male <input type="radio" name="Gender" <?php if(isset($Gender)&& $Gender=="Female") echo "checked"; ?> Value="Female">Female</div>
<span class="error"><?php echo $genderErr;?></span>
<div class="inp">Date Of Birth</div>
<div class="inp1"><select name="DayOfBirth"><option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option></select> <select name="MonthOfBirth"><option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option></select> <select name="YearOfBirth"><option>1970</option>
<option>1971</option>
<option>1972</option>
<option>1973</option>
<option>1974</option></select></div>
<span class="error"><?php echo $dobErr;?></span>
<span class="error"><?php echo $mobErr;?></span>
<span class="error"><?php echo $yobErr;?></span>
<div class="inp2"><input type="submit" name="submit" value="SIGN UP"></div></div>
</form>
signup.php
<?php
include ('project1db.php');
//Define variables
$fullnameErr="";
$emailErr="";
$passwordErr="";
$conpasswordErr="";
$genderErr="";
$dobErr="";
$mobErr="";
$yobErr="";
$FullName="";
$Email="";
$Password="";
$ConfirmPassword="";
$Gender="";
$DayOfBirth="";
$MonthOfBirth="";
$YearOfBirth="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["FullName"])){
$fullnameErr = "Name is required";
}
else{
$FullName = test_input($_POST["FullName"]);
//Check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z]*$/",$FullName)){
$fullnameErr = "Enter Valid name please!";
}
}
if(empty($_POST["Email"])){
$emailErr = "Email is required";
}else{
$EMail = test_input($_POST["Email"]);
//Check if e-mail address is correct
if(!filter_var($EMail, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email address";
}
}
if(empty($_POST["Password"])){
$passwordErr = "Password is required";
}else{
$Password = test_input($_POST["Password"]);
//Check password
if(!preg_match("/^[a-z0-9]{6,}$/",$Password)){
$passwordErr = "Password should contain 6+ characters, lowercase and numbers!";
}
}
if(empty($_POST["ConfirmPassword"])){
$conpasswordErr = "Confirm your Password!";
}
else{
$ConfirmPassword = test_input($_POST["ConfirmPassword"]);
//Confirm if password match
if($ConfirmPassword != $Password){
$conpasswordErr = "Password not match!";
}
}
if(empty($_POST["Gender"])){
$genderErr = "Select your Gender!";
}else{
$Gender = test_input($_POST["Gender"]);
}
if(empty($_POST["DayOfBirth"])){
$dobErr = "Select your Day Of Birth";
}else{
$DayOfBirth = test_input($_POST["DayOfBirth"]);
}
if(empty($_POST["MonthOfBirth"])){
$mobErr = "Select your Month Of Birth";
}else{
$MonthOfBirth = test_input($_POST["MonthOfBirth"]);
}
if(empty($_POST["YearOfBirth"])){
$yobErr = "Select your Year Of Birth";
}else{
$YearOfBirth = test_input($_POST["YearOfBirth"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = ""){
$sql = "INSERT into usersignup (FullName, Email, Password, Gender, DayOfBirth, MonthOfBirth, YearOfBirth) VALUES(?,?,?,?,?,?,?)";
if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssssisi", $FullName, $Email, $Password, $Gender, $DayOfBirth, $MonthOfBirth, $YearOfBirth);
/* Set the parameters values and execute
the statement again to insert another row */
$FullName = $_REQUEST['FullName'];
$Email = $_REQUEST['Email'];
$Password = $_REQUEST['Password'];
$Gender = $_REQUEST['Gender'];
$DayOfBirth = $_REQUEST['DayOfBirth'];
$MonthOfBirth = $_REQUEST['MonthOfBirth'];
$YearOfBirth = $_REQUEST['YearOfBirth'];
$stmt->execute();
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
}
else{
}
?>
Database Connection
project1db.php
<?php
$dbhost = 'localhost:3308';
$dbuser = 'root';
$dbpass = '';
$dbname = 'phpproject';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: '.mysqli_error());
}
echo 'Connected successfully';
I have figured out the problem and the problem have been solved.
First problem is with the Mysql database. The AutoIncrement colunm precisely was not set to AutoIncrement. So, I open PhpMyadmin to alter and set the Id colunm to AutoIncrement.
Second Problem was with the conditional statement here:
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = "")
The correct line of code which later worked properly is:
if(empty($fullnameErr) && empty($emailErr) && empty($passwordErr) && empty($conpasswordErr) && empty($genderErr) && empty($dobErr) && empty($mobErr) && empty($yobErr))
This is an important information for those who got confused after they have validated the data input but didn't know how to save the data into the database table.
Related
index.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color:red;
}
</style>
</head>
<body>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = "";
$name = $email = $username = $password = $DateOfBirth = $department = $age = "";
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 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["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 and white space allowed";
}
}
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"]);
}
if ($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "") {
$check = "SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli, $check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($da[0] > 1) {
echo "Username Already in Exists<br/>";
}
else {
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,
`Date_of_birth` , `department` ,`age`)
VALUES ('','" . $username . "', '" . $hashed_password . "', '" . $email . "' ,
'" . $name . "' , '" . $DateOfBirth . "' , '" . $department . "' , '" . $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">
<h2>Registration Form</h2>
<p><span class="error">All fields are required </span></p>
<form method="post" action="">
Name:
<input type="text" name="name" style="margin-left: 52px">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email" style="margin-left: 48px">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
Username:
<input type="text" name="username" style="margin-left:26px">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
Password:
<input type="password" name="password" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
Date Of Birth :
<input type="date" name="Date_of_birth">
<span class="error"> <?php echo $DateOfBirthErr;?></span>
<br><br>
Age :
<input type="number" name="age" style="margin-left:62px">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
Department :
<select name="department" style="margin-left:14px">
<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>
<input type="submit" name="submit" value="Register">
</form>
</div>
</body>
</html>
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'amith';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
i'm creating a simple php registration form, i only have one issue which is not getting fixed i.e., when any one while registering enters the same username then an error message should throw saying that username already taken i have tried with the above code but its not working. please can any one help me to fix my issue.
before
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` ,
`name` , `Date_of_birth` , `department` ,`age`)
VALUES ('','".$username."', '".$hashed_password."', '".$email."' ,
'".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."')";
You can write SQL to check if username is exist or not :
SQL : 'SELECT username from users where username = $username';
If this query returns result with count more than 0 then show an error message as 'This Username already exists';
If it gives you 0 results then proceed with INSERT functionality.
Before you insert the new user you can query for the username with a select like:
SELECT username FROM users WHERE username='$username'
If this query returns more than 0 rows the username exists already.
Hi you can try like this
variable should be like this $_POST['username']
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,`Date_of_birth` , `department` ,`age`) VALUES ('', ".$username.", ".$hashed_password.", ".$email." , ".$name." , ".$DateOfBirth." , ".$department." , ".$age.")";
An effective way to tackle this unique username problem is to validate the username at the time of entry from UI.
Step 1:in html input box there should be jquery or js function call to a php page with entered username as argument.
Step 2 the backend php scrpt will simple check the username in database and if exists the will return a JSON o/p that userbane alreasy exist else it will return true.
Step 3:show the message to on UI with simple Js and block further processing of form.
Also you must check the uniqueness of username after form submit and before insert into your data base table to avoid concurrent submit by two different user with same username.
Also if possible make sure username is primary key in your database table to avoid concurrent submit with same username problem,This will add another solid layer of protection at the bottom.
<input type="text" name="uname" id="uname" onblur="unameOnBlur(this.value);">
You can do it onkeyup or any suitable event also.
inside unameOnBlur make an ajax call like
$.ajax({
url: 'json_uname.php?uname=' + uname,
dataType: 'json'
}).done(function (j){
if(username unique)
//your action code
})
the above one is sample ajax call example
Json_uname.php page is simple to write to check against db.
Hi i am trying to build a form and insert the data to my db it's working perfect now i want to make it validation using php to prevent span inputs i am beginner at php so p;ease i need help with this
and the php code
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$con = mysqli_connect('localhost','root','');
if(!$con)
{echo'not connect';}
if(!mysqli_select_db($con,'form'))
{echo'not selected';}
$name=$_POST['name'];
$phone=$_POST['phone'];
$nationality=$_POST['nationality'];
$country=$_POST['country'];
$sql = "INSERT INTO newform(Name,Number,Nationality,Country) VALUES('$name','$phone','$nationality','$country')";
if(!mysqli_query($con,$sql))
{echo'not insert';}
else
{
echo'insertes';
}
header("refresh:2;url=form.php");
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$error = false;
$nameErr = $phoneErr = $nationalErr = $countErr = "";
$con = mysqli_connect('localhost','root','');
if(!$con)
{
echo 'not connect';
}
if(!mysqli_select_db($con,'form'))
{
echo' DB not selected';
}
if(isset($_POST['submit'])){
$name=$_POST['name'];
$phone=$_POST['phone'];
$nationality=$_POST['nationality'];
$country=$_POST['country'];
if($name ==""){
$error = true;
$nameErr = "Name field is empty";
}
if($phone ==""){
$error = true;
$phoneErr = "phone field is empty";
}
if($nationality ==""){
$error = true;
$nationalErr = "nationality field is empty";
}
if($country ==""){
$error = true;
$countErr = "country field is empty";
}
if($error == false){
$sql = "INSERT INTO newform(Name,Number,Nationality,Country) VALUES($name,$phone,$nationality,$country')";
if(!mysqli_query($con,$sql))
{
echo 'Values not insert';
}else
{
header("refresh:2;url=form.php");
}
}
}
?>
<form method="post">
First name:<br>
<input type="text" name="name">
<p style="color:red"><?php echo $nameErr ?></p>
<br>
phone:<br>
<input type="text" name="phone">
<p style="color:red"><?php echo $phoneErr ?></p>
<br><br>
Nationality:<br>
<input type="text" name="nationality">
<p style="color:red"><?php echo $nationalErr ?></p>
<br><br>
Country:<br>
<input type="text" name="country">
<p style="color:red"><?php echo $countErr ?></p>
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
Please i need help with this form i have those problems Please help me
1- When it submit write error but i see in PHPMyAdmin it's added and record in MySql Database
Example:
Error: INSERT INTO clients (name, email, website, comment, gender) VALUES ('', '', '', '', '')
2- When i don't fill and a required field i see the error message but it's added and record in MySql Database
Example
Email is required
my code is below
<?php
// Database information
$servername = "localhost";
$username = "mymbnwye_mexx";
$password = "";
$dbname = "";
// Database connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// Check input
function checker_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = checker_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = checker_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = checker_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = checker_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = checker_input($_POST["gender"]);
}
$sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
This should work for the PDO Database:
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
I added an If statement to the connection.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_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 = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<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
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_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 = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<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
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>
using code that you have mentioned, your sql query will always execute event if there is empty fields because you are writing your query outside of condition.
This code will help solving your problem
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$name = checker_input($_POST["name"]);
$gender = checker_input($_POST["gender"]);
$comment = empty($_POST["comment"]) ? "" :checker_input($_POST["comment"]);
$website = empty($_POST["website"]) ? "" :checker_input($_POST["website"]);
$email = checker_input($_POST["email"]);
$sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Your code doesn't stop the query being executed if there are missing values. Try something like this instead:
function ValuesCompleted()
{
$values = Array('name', 'email', 'gender');
foreach($values as $index)
{
if(empty($_POST[$index]))
{
return "{$index} not supplied";
}
}
return true;
}
if(isset($_POST) && ValuesCompleted() === true)
{
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$statement = $conn->prepare("INSERT INTO clients (name, email, website, comment, gender)
VALUES (?, ?, ?, ?, ?)");
$statement->execute(Array($_POST['name'], $_POST['email'], $_POST['website'], $_POST['comment'], $_POST['gender']);
$conn = null;
}
catch(PDOException $e)
{
// ideally you would print this to a log, not echo it.
echo($e->getMessage());
}
}
else
{
echo ValuesCompleted();
}
I'm trying to insert data into the 'riders' table in the 'poo12104368' database using a form. Currently I am having problems with my 'if' statements because they are not working as they should be. For example, if a user was to only type in a last name and an email address, it would let them create an account. When the user does create an account by entering their correct details into the feilds it should take them to 'newaccount.php'. Can anybody help? Thanks
Code:
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
echo "Something is wrong";
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
echo "<b>Please enter a first name</b>";
}
else if($_POST['lastname'] == null){
echo "<b><p>Please enter a last name</p></b>";
}
else if($_POST['suemail'] == null){
echo "<b><p>Please enter an email</p></b>";
}
$dblink = mysql_connect("localhost", "root", "" )
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required inputs
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
Try this it will work :
Use flag to handle the validation errors in the form use this $error as a flag.
Code :
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
$error = 0;
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
$msg = "something going wrong";
$error = 1;
}
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
$error = 1;
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
$error = 1;
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
$error = 1;
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
$msg = "Please enter a first name";
$error = 1;
}
else if($_POST['lastname'] == null){
$msg = "Please enter a last name";
$error = 1;
}
else if($_POST['suemail'] == null){
$msg = "Please enter an email";
$error = 1;
}
if($error == '0')
{
$dblink = mysql_connect("localhost", "root" , "")
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required standards
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
else
{
echo $msg;
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
I hope it will work for you.
I'm developing a user registration and login for a an app using jQuery and PHP. I am having trouble inserting a record into my members database. When I click submit I'm getting the "Not Registered" alert., it just takes me back to the registration page.
My jQuery handle for the submit button and the HTML:
$('#regsubmit').click(function(){
$.post("register.php",{reguser: $("#reguser").val(), fname: $("#fname").val(),lname: $("#lname").val(),regpass: $("#regpass").val(), regemail: $("#regemail").val()},function(data){
if(data == true){
alert("Registered");
}else{
alert("Not Registered");
}
});
});
<div data-role="content">
<div data-role="collapsible"><h2>Register</h2>
<form action="" method="post" id="registrationform">
<div data-role="fieldcontain">
<label for="fname">First name:</label>
<input type="text" name="fname" id="fname" value="" />
<div id="fnamecheck"></div>
</div>
<div data-role="fieldcontain">
<label for="lname">Last name:</label>
<input type="text" name="lname" id="lname" value="" />
<div id="lnamecheck"></div>
</div>
<div data-role="fieldcontain">
<label for="regemail">Email:</label>
<input type="email" name="regemail" id="regemail" value="" />
<div id="emailcheck"></div>
</div>
<div data-role="fieldcontain">
<label for="reguser">Username:</label>
<input type="text" name="reguser" id="reguser" value="" />
<div id="usernamecheck"></div>
</div>
<div data-role="fieldcontain">
<label for="regpass">Password:</label>
<input name="regpass" type="password" id="regpass" value="">
<div data-role="fieldcontain"><label for="confirmregpass">Confirm Password:</label>
<input name="confirmregpass" type="password" id="confirmregpass" value=""></div>
</div>
<input name="regsubmit" type="submit" id="regsubmit" value="Register" data-icon="check" data-theme="a"/>
</form>
</div>
And my register.php:
<?php
$MYSQL_SERVER = "localhost";
$MYSQL_USER = "root";
$MYSQL_PASSWORD = "password";
$db = mysql_connect($MYSQL_SERVER, $MYSQL_USER, $MYSQL_PASSWORD ) or die(mysql_error());
mysql_select_db("hedonsof_conflict") or die(mysql_error());
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['regemail'];
$reguser = $_POST['reguser'];
$regpass = $_POST['regpass'];
//Username check
$usercheck = mysql_query("SELECT * FROM members WHERE username='".$reguser."'");
if(empty($fname)||empty($lname)||empty($email)||empty($reguser)||empty($regpass)){
if(empty($fname)){
$errors[] = "Missing first name.";
}
if(empty($lname)){
$errors[]= "Missing last name.";
}
if(empty($email)){
$errors[]= "Missing email.";
}
if(empty($reguser)){
$errors[]= "Missing user name.";
}
if(empty($regpass)){
$errors[] = "Missing password.";
}
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors = "Not a valid eail address.";
}else{
$fname = strip_tags($fname);
$fname = stripslashes($fname);
$fname = trim($fname);
$lname = strip_tags($lname);
$lname = stripslashes($lname);
$lname = trim($lname);
$email = strip_tags($email);
$email = stripslashes($email);
$email = trim($email);
$reguser = strip_tags($reguser);
$reguser = stripslashes($reguser);
$reguser = trim($reguser);
$regpass = strip_tags($regpass);
$regpass = stripslashes($regpass);
$regpass = trim($regpass);
$sql = mysql_query("INSERT INTO members (username, fname, lname, password, email) VALUES('$reguser','$fname','$lname','$regpass','$email)") or die(mysql_error());
$msg = "Thanks for Registering.";
if($msg){
echo true;
}else{
$errors[] = "Sorry error with database at this time.";
echo $errors;
}
}
?>
EDIT:
<?php
$MYSQL_SERVER = "localhost";
$MYSQL_USER = "root";
$MYSQL_PASSWORD = "password";
$db = mysql_connect($MYSQL_SERVER, $MYSQL_USER, $MYSQL_PASSWORD ) or die(mysql_error());
mysql_select_db("hedonsof_conflict") or die(mysql_error());
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['regemail'];
$reguser = $_POST['reguser'];
$regpass = $_POST['regpass'];
$errors[] = "";
//Username check
$usercheck = mysql_query("SELECT * FROM members WHERE username='".$reguser."'");
if(empty($fname)){
$errors[] = "Missing first name.";
}
if(empty($lname)){
$errors[]= "Missing last name.";
}
if(empty($email)){
$errors[]= "Missing email.";
}
if(empty($reguser)){
$errors[]= "Missing user name.";
}
if(empty($regpass)){
$errors[] = "Missing password.";
}
// }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
// $errors = "Not a valid email address.";
else{
$fname = strip_tags($fname);
$fname = stripslashes($fname);
$fname = trim($fname);
//$fname = mysqli_real_escape_string($fname);
$lname = strip_tags($lname);
$lname = stripslashes($lname);
$lname = trim($lname);
//$lname = mysqli_real_escape_string($lname);
$email = strip_tags($email);
$email = stripslashes($email);
$email = trim($email);
//$email = mysqli_real_escape_string($email);
$reguser = strip_tags($reguser);
$reguser = stripslashes($reguser);
$reguser = trim($reguser);
//$reguser = mysqli_real_escape_string($reguser);
$regpass = strip_tags($regpass);
$regpass = stripslashes($regpass);
$regpass = trim($regpass);
//$regpass = mysqli_real_escape_string($regpass);
$sql = mysql_query("INSERT INTO members (username, fname, lname, password, email) VALUES('$reguser','$fname','$lname','$regpass','$email')") or die(mysql_error());
$msg = "Thanks for Registering.";
if($msg){
echo "true";
}else{
$errors[] = "Sorry error with database at this time.";
echo "false";
}
}
?>
Try this:
$('#regsubmit').click(function(e){
e.preventDefault();
$.post("register.php",{reguser: $("#reguser").val(), fname: $("#fname").val(),lname: $("#lname").val(),regpass: $("#regpass").val(), regemail: $("#regemail").val()},function(data){
if(data == true){
alert("Registered");
}else{
alert("Not Registered");
}
});
return false;
});