PHP form to insert into database, check for nothing entered - php

My question is, how do I get the form to display an error when the user doesn't input a field into the form. I can get it to work when they don't fill out the form at all and just hit enter, but cannot get it to work if they only fill out a few fields. They could fill out the title field and the run time field and will be able to submit it. How can I get it to make sure that every field is filled out?
<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
if(isset($_POST['submit'])) {
$value = mysqli_real_escape_string($conn,$_POST['title']);
$value2 = mysqli_real_escape_string($conn,$_POST['rating']);
$value3 = mysqli_real_escape_string($conn,(int)$_POST['Runtime']);
$value4 = mysqli_real_escape_string($conn,(float)$_POST['movie_rating']);
$value5 = mysqli_real_escape_string($conn,$_POST['release_date']);
// Checks for empty fields
if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
echo 'Please correct the fields';
return false;
}
// Concatenate the $values into the string
$sql = "INSERT INTO movies(title,rating,Runtime,movie_rating,release_date)
VALUES('$value','$value2','$value3','$value4','$value5')";
if ($conn->query($sql)) {
$msg = "New record created successfully";
} else {
$msg = "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<form method="post"/>
<p>Enter Movie Title: <input type="text" name="title"/></p>
<p>Enter Movie Rating(G,PG,PG-13,R): <input type="text" name="rating"/></p>
<p>Enter Movie Runtime in minutes: <input type="text" name="Runtime"/></p>
<p>Enter IMDB Movie Rating(0-10.0): <input type="text" name="movie_rating"/></p>
<p>Enter Movie Release date(YYYY-MM-DD): <input type="text" name="release_date"/></p>
<button type="submit" name="submit">Submit</button
</form>
<?php
if (isset($msg)) {
echo $msg;
}
?>

From Front side you can add required attribute to each input. So add it in every input field like :
<input type="text" name="title" required/>
From back-end side (using PHP) If you want all value must be fill up then change && with || in your condition
// Checks for empty fields
if (empty($value) || empty($value2) || empty($value3) || empty($value4) || empty($value5)) {
echo 'Please correct the fields';
return false;
}

if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
echo 'Please correct the fields';
return false;
}
This should be 'or'

Related

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

php /mysql form validation issue

so my php validation has two check functions, first it checks for an empty name or password entry and second if user enters unwanted characters while entering his name, the problem is that if the user does enter an unwanted character or numbers in the 'name' entry the form is still saved to the database which it should not, nothing is saved to the database if the users leaves both the name and password field empty and the error is shown, which means half of my validation check is working fine . can any one help me out ?
<?php
// Connect to data base
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$nameErr = $userpasswordErr = "";
$name = $userpassword = "";
//check for error
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//validate name and password
if (
empty($_POST["name"]) ||
empty($_POST["userpassword"] ||
!preg_match("/^[a-zA-Z ]*$/",$name))
) {
$nameErr= "* Incorrect username or password ";
} else {
$name = test_input($_POST["name"]);
$userpassword = test_input($_POST["userpassword"]);
$sql = "INSERT INTO users(name,email)
VALUES ('$name','$userpassword')";
if ($conn->query($sql) === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<span class="error"></span>
<form method="post" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?>">
name : <input type="text" name="name" value="<?php echo $name;?>"/>
<span class="error"><?php echo $nameErr ;?> </span>
<br/><br/>
password : <input type="text" name="userpassword" value="<?php echo $userpassword ; ?>">
<span class="error"><?php echo $userpasswordErr ;?> </span>
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
The $name in regular expression check should be $_POST['name']
if(empty($_POST["name"]) || empty($_POST["userpassword"] || !preg_match("/^[a-zA-Z ]*$/",$_POST["name"])))
{
$nameErr= "* Incorrect username or password ";
}

MySQL database not selected. where did I miss it?

After searching through related questions, I still couldn't get this issue resolved. A "registration successful" page is supposed to pop up after a form is submitted but instead, "No database selected" message appears. where did I miss it. here are the codes.
connect.php
<?php
//connect.php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'esiro';
$connection = mysqli_connect($server, $username, $password, $database);
mysqli_set_charset($connection,"utf8");
?>
signup.php
<?php
//signup.php
include 'connect.php';
include 'header.php';
echo '<h3>Sign up</h3>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo
'<form role="form" method="post" action="" class="cover_form">
<div class="form-group">
<label class="labelfield" for="username">User Name:</label><br>
<input class="inputfield" type="text" name="user_name" class="form-control"/><br>
<label class="labelfield" for="pwd">Password:</label><br>
<input class="inputfield" type="password" class="form-control" id="pwd" name="user_pass"><br>
<label class="labelfield" for="pwd"> Confirm Password:</label><br>
<input class="inputfield" type="password" name="user_pass_check" class="form-control" id="pwd"><br>
<label class="labelfield" for="email">Email Address:</label><br>
<input class="inputfield"type="email" class="form-control" id="email" name="user_email">
</div><br>
<input type="submit" class="btn btn-default" value="Complete Registration"/><br>
</form>
';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(isset($_POST['user_name']))
{
//the user name exists
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'The username can only contain letters and digits.';
}
if(strlen($_POST['user_name']) > 30)
{
$errors[] = 'The username cannot be longer than 30 characters.';
}
}
else
{
$errors[] = 'The username field must not be empty.';
}
if(isset($_POST['user_pass']))
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
else
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly...';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysql_real_escape_string($_POST['user_email']) . "',
NOW(),
0)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
echo 'Successfully registered. You can now sign in and start posting! :-)';
}
}
}
include 'footer.php';
?>
You should Change the script
$result = mysql_query($sql);
Instead of use this
---------------------
$result = mysqli_query($connection,$sql);
And also remove echo mysql_error();
and use this echo mysql_error($connection);
Add this also in instead of mysql_real_escape_string
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysqli_real_escape_string($connection,$_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysqli_real_escape_string($connection,$_POST['user_email']) . "',
NOW(),
0)";

Need advice / guidance on makin registration form

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}

PHP Form Validation Showing Errors Before Submission

I am working on making a PHP and MySQL application for practicing my new-found love for programming. I have a login script; the HTML form is as follows:
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input type="text" name="username" maxlength="60"><br />
Password:
<input type="password" name="password" maxlength="60"><br />
Confirm Password:
<input type="password" name="password_confirm" maxlength="60"><br />
<input type="submit" name="submit" value="Register"><br />
</form>
This continues into the PHP form validator:
<?php
$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];
//This makes sure they did not leave any fields blank
function FieldComplete($user, $password, $password_confirm) {
if (!isset($user, $password, $password_confirm) &&
$user && $password && $password_confirm == "" || " ") {
$field_confirm = false;
} else {
$field_confirm = true;
}
if ($field_confirm == true) {
echo "";
} else {
echo "You did not complete all the required fields.";
}
}
FieldComplete($username_original, $password_original, $password_confirm_original);
?>
I realize that making a function for this might seem a little useless, but it was as close as I got to the result I wanted.
However, this code displays the error "You did not complete all the required fields." on loading of the page. I only want that error to display if they have pressed the register button and still have a blank field.
Any advice or help is greatly appreciated. Thanks StackOverflow community!
If you want to run the php code only if button is submitted so you need to check about that at the top of your page
if(isset($_POST["submit"]))
{
//form has been submitted
//do validation and database operation and whatever you need
} else {
//form has not been submitted
//print the form
}
In addition to Fabio answer, you can improve your code like this:
if(isset($_POST['submit'])){
$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];
$isComplete = FieldComplete($username_original, $password_original, $password_confirm_original);
if(!$isComplete){
echo "You did not complete all the required fields.";
}
}else{
//display the form
}
function FieldComplete($user, $password, $password_confirm) {
if (!isset($user, $password, $password_confirm) &&
$user && $password && $password_confirm == "" || " ") {
return false;
} else {
return true;
}
}

Categories