Previous data auto insert when browser reloading in PHP - php

I have some data input area.Here is my file.
Here is my db.php:
<?php
$username = "root";
$password = "";
try {
$db = new PDO('mysql:host=localhost;dbname=task', $username, $password);
echo "Connection Successfull";
} catch (PDOException $e) {
die("Error: Database connection");
}
?>
And my index.php is:
<?php
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" value="Submit">
</form>
</div>
<?php
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
?>
</body>
</html>
When i first go to index.php page then it's showing some notice.
Notice: Undefined index: name in
C:\xampp\htdocs\techmasters\begin\index.php on line 21
Notice: Undefined index: email in
C:\xampp\htdocs\techmasters\begin\index.php on line 22
Notice: Undefined index: website in
C:\xampp\htdocs\techmasters\begin\index.php on line 23
but if i input any data then it going to be inserted fine.My problem is that if i reload the browser then previous inserted data going to inserted again.How can i solve this problem?
Thanks in advanced.

Its because, you are not checking whether form is submitted or not.
On every page request, data is getting inserted, add a check.
<?php
if (isset($_POST['name']) && ! empty($_POST['name'])) {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if (empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
$_POST = NULL;
}
?>
This will ensure that database insert will be done only in case of form submit.
EDIT:
If you submit a form to same page and then reload the page, it will
ask you to resubmit the form. Either change method to get and check
for duplicity or submit the form to another file (move form submit
code to other file and set it as form action).

When you reload the page it's asking for form re-submission. When you click on resend then it will post all data again and inserted in database. To overcome this issue you can use jquery.
Try this code :
html file :
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" id="frm" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" class="sub" value="Submit">
</form>
</div>
<script>
$(".sub").click(function (e) {
e.preventDefault();
$.post("test.php",$("#frm").serialize(),function(data){
if(data == "Inserted!") {
//You can reload your page here
} else {
//Display error message.
}
});
});
</script>
</body>
</html>
You php code (test.php) :
<?php
include "db.php";
if(isset($_POST['name']) && $_POST['name'] != "") {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
} else {
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
exit;
}
?>
Don't forget to add jquery file in your html.

Related

Undefined index PHP for a registration form

<?php
include('connection.php');
$username = $_POST['user'];
$password = $_POST['pass'];
//to prevent from mysqli injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$sql = "select *from login where username = '$username' and password = '$password'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1){
echo "<h1><center> Login successful </center></h1>";
}
else{
echo "<h1> Login failed. Invalid username or password.</h1>";
}
?>
I have to do a website that works like google forms, for school. The thing is that in the signup form I get this error and I don t understand why I'm pretty new to the whole PHP stuff and I didn't find much about this error.
The HTML file
<html>
<head>
<title>PHP Signup system</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="frm">
<h1>Signup</h1>
<form name="f1" action="registration.php" onsubmit="return validation()" method="POST">
<p>
<label> UserName: </label>
<input type="text" id="user" name="Username" />
</p>
<p>
<label> Password: </label>
<input type="password" id="pass" name="Password" />
</p>
<p>
<label> Password: </label>
<input type="password" id="passc" name="Confirm Password" />
</p>
<p>
<label> Email: </label>
<input type="text" id="email" name="Email" />
</p>
<p>
<input type="submit" id="btn" value="Submit" />
</p>
</form>
</div>
<script>
function validation() {
var id = document.f1.user.value;
var ps = document.f1.pass.value;
var psc = document.f1.passc.value;
var em = document.f1.email.value;
if (id.length == "" && ps.length == "") {
alert("User Name and Password fields are empty");
return false;
} else {
if (id.length == "") {
alert("User Name is empty");
return false;
}
if (ps.length == "") {
alert("Password field is empty");
return false;
}
if (em.length == "") {
alert("Email field is empty");
return false;
}
if (ps != psc) {
alert("Passwords do not match");
return false;
}
}
}
</script>
</body>
</html>
It is pretty simple, and it doesn't have to look good, just to work.
EDIT: I got it, the problem was in fact that I misused the post method and names and that after that I forgot to make the connection with the database. credits to the guy in comments
Your post value is not set.
$_POST['foo'] // <== if not set or falsy, returns an undefined index warning
You must check if $_POST is populated before proceeding to execute you backend logic. Place the following at the top of your script and replace foo on your input's name.
if(!isset($_POST['foo']) || !$_POST['foo']){
// $_POST is not set. Notify user then exit!
echo 'Field "foo" is required!';
exit;
}
Or if your submit functions are in the same file of your form, try this:
if(isset($_POST['foo']) && $_POST['foo']){
// place your backend logic here to ensure that the required field(s) are field
}

Registration form validation problem using php and tetxt file

I created a registration form which is working fine. I save all of my users data in a txt file named users.txt which saves the the data after the button click like this:
username|password|email
here is my users.txt file:
asd|asd|asd
asd|asd|asd
sanyi|123456|asd#asd.hu
sanyi|123456|asd#asd.hu
sanyi|123456|asd#asd.hu
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
I want to solve that the username must be unique! I tried to solve this by check the txt file before the registration and if I find the same username in the txt that the user submitted, kill the process. I can check the first line username but I have no idea how I can go to the next line, and so on...
My php code:
register.php:
<!-- html section -->
<!DOCTYPE html>
<html>
<head>
<title>Store form data in .txt file</title>
</head>
<body>
<form action="#" method="post">
REGISTRATION<br />
<input type="text" name="username" placeholder = "Username"/><br />
<input type="text" name="password" placeholder = "Password" /><br />
<input type="text" name="password2" placeholder = "Password Again"><br />
<input type="text" name="email" placeholder = "Email Adress"/><br />
<input type="submit" name="submit" value = "REGISTER" />
</form>
</body>
</html>
<!-- php section -->
<?php
if(isset($_POST['submit']))
{
//check if the username has been already taken
$usernameToCheck = $_POST["username"];
$userlist = file ('users.txt');
$success = false;
foreach ($userlist as $user) {
$user_details = explode('|', $user);
if ($user_details[0] == $usernameToCheck) {
die("This user is already exsists");
}
}
// the registreation itself
$username = $_POST["username"];
$password = $_POST["password"];
$password2 = $_POST["password2"];
$email = $_POST["email"];
if(empty($username) || empty($password) || empty($password2) || empty($email)){
die("You filled out the form wrongly! Don't let anything empty next time!");
}else if($password !== $password2){
die("Passwords doesnt match!");
}else{
$fp = fopen('users.txt', 'a');
$line = $username."|".$password."|".$email.PHP_EOL;
fwrite($fp, $line);
fclose($fp);
}
}
?>

php - FILTER _VALIDATE_EMAIL check

I have a PHP script where I want to verify a valid email address using filter_var() but it is not working.
html form:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CRUD Operations</title>
</head>
<body>
<div id="container"><!--container-->
<div id="wrapper">
<div id="form-element">
<div id="headings">
<h1>PHP Contact Form</h1>
</div>
<form method="post" action="operations.php" enctype="multipart/form-data">
<span>Name:</span><br>
<input type="text" name="name" value=""><br><br>
<span>Email:</span><br>
<input type="text" name="mail" value=""><br><br>
<span>Gender:</span><br>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
<span>Message</span><br>
<div id="message">
<textarea cols="36" rows="4" name="message"></textarea><br>
</div>
<div id="submit">
<input type="submit" value="Submit" name="submit">
</div>
</form>
</div>
</div>
</div><!--container-->
</body>
</html>
php code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CRUD Operations</title>
</head>
<?php
include_once('config.php');
$name = $mail = $gender = $message = '';
$email_err = '';
if(isset($_POST['submit'])){
$name= $_POST['name'];
$mail = $_POST['mail'];
if(!isset($_POST['gender'])){
}
else {
$gender = $_POST['gender'];
}
$message = $_POST['message'];
if(empty($name) || empty($mail) || empty($gender)|| empty($message)) {
if(empty($name)){
echo'<div class="error">*Dear User fill the Name field properly</div>';
}
if(empty($mail)){
echo'<div class="error">*Dear User fill the Email field properly</div>';
}
else {
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)){
$email_err = "*valid Email is required";
}
}
if(empty($gender)){
echo'<div class="error">*Dear User please select your gender</div>';
}
if(empty($message)){
echo'<div class="error">*Dear User please Leave your Message</div>';
}
}
else {
$query = mysql_query("INSERT INTO users(`name`, `mail`, `gender`, `message`) VALUES('".$name."','".$mail."','".$gender."','".$message."')");
if($query) {
echo '<div class="success">Congratulations You Are Registered Successfully</div>';
echo 'View Records';
}
else {
echo 'not';
}
}
}
?>
</html>
Any help would be appreciated!
You're setting the validation error to the $email_err variable, but you're not doing anything with that variable after that.
But more importantly, the filter_var() call will never be hit. You have it in the block that checks for any of $name $mail $gender $messsage are empty. So the only way to get your code to do an email validation would be if someone entered an email address, but left gender blank.
You need to move the filter_var() call out of that block:
if(empty($name) || empty($mail) || empty($gender)|| empty($message)) {
if(empty($name)){
echo'<div class="error">*Dear User fill the Name field properly</div>';
}
if(empty($mail)){
echo'<div class="error">*Dear User fill the Email field properly</div>';
}
if(empty($gender)){
echo'<div class="error">*Dear User please select your gender</div>';
}
if(empty($message)){
echo'<div class="error">*Dear User please Leave your Message</div>';
}
}
elseif(!filter_var($mail, FILTER_VALIDATE_EMAIL)){
echo'<div class="error">*valid Email is required</div>';
}
else {
$query = mysql_query("INSERT INTO users(`name`, `mail`, `gender`, `message`) VALUES('".$name."','".$mail."','".$gender."','".$message."')");
if($query) {
echo '<div class="success">Congratulations You Are Registered Successfully</div>';
echo 'View Records';
}
else {
echo 'not';
}
}
When I write validation code such as this I try to avoid using conditionals that check so many things at once. Instead, validate each input in turn and abort if that is not valid; returning an error to the user at that point. Then you could move all of this validation to a single sub-routine. In this routine, if any validation checks fail - it returns immediately with an error. Only if your sub-routine makes it to the end would a user be created. And it prevents one from checking a variable $mail and then later validating it after it's already passed your truth check.

stop repeat the actions on the page after submit the form

Stop repeat the actions on the page after submit the form
I made this "sign in" form and made a error messages to appear if the fields is empty and other error messages.
my request is:
After the "sign in" fails how to stop the fields from resubmit the values again when hit F5 or reload the page.
<?php
ob_start();
session_start();
include "config/config.php";
include "includes/functions/check.php";
$userName = $passWord = "";
$userNameErr = $passWordErr = $loginErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[a-zA-Z ]*$/", $userName)) {
$userNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['password'])) {
$passWordErr = "Password is required";
} else {
$passWord = check_input($_POST['password']);
}
$loginUser = $db->prepare("SELECT * FROM hired_person_info WHERE user_name=? AND password=?");
$loginUser->bind_param('ss', $userName, $passWord);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$_SESSION['name'] = $row->full_name;
$_SESSION['log'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "Invalid Login Information";
}
}
}
ob_flush()
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Administration Panel</title>
<link href="../css/adminStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 id="head" class="header_height"></h1>
<div class="contentLogin">
<div class="login_bg">
<div id="header">
<p>login</p>
</div>
<div id="form">
<?php
echo $loginErr;
?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="user_name" class="text_login">User name</label>
<input type="text" name="user_name" id="user_name" value="<?php echo $userName ?>">
<?php echo $userNameErr; ?>
<br/><br/>
<label for="password" class="text_login">Password</label>
<input type="password" name="password" id="password">
<?php echo $passWordErr; ?>
<br/>
<div id="submit">
<input type="submit" value="Sign in" name="submit" id="submit" class="btn">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Instead of using if($_SERVER["REQUEST_METHOD"] == "POST"){ try using the post name of your submit button. So the condition will be as follows,
if(isset($_POST['submit'])) {
}
Within this you can put all your codes. I am not telling that the condition you have used is wrong, but it may create conflict when you will put another form in the same page.
And after your operation completed, success or fail, does not matter just unset the post variable.
unset($_POST);
To completely avoid the resend functionality you need to redirect your page to the same page once. For that just save your error message in session and redirect to login page again. Then checking if session value for message exists then display your message.

Showing form errors on a dropdown form

my title might sound strange so I'll try to explain it better in here.
I have a login form that is hidden when you visit the page. It's located in the upper right corner as a small dropdown form. This is the code without the Jquery since I think it isn't needed for my problem:
<!DOCTYPE html>
<?php
include "core/init.php";
?>
<html>
<head>
<title>Swimstats</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<header>
<div id="border"></div>
<div id="login">
<div id="userName" class="toggleOff">
<?php
if(logged_in() === true){
echo '<p>Welcome ' . $_SESSION['userID'] . '</p>';
} else {
?>
<p>Have an account? <span id="test">Sign in here!</span></p>
<?php } ?>
</div>
<div id="login-content">
<form class="clearfix" action="checkuser.php" method="post">
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
</div>
</header>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
SO a simple dropdown form, but I whenever the user fills in faulty credentials or leaves something empty or whatever I need to show an error under the form or above, doesn't matter. I have the following code to catch the errors:
<?php
include "core/init.php";
if(empty($_POST) === false){
$email = $_POST['email'];
$password = $_POST['password'];
if(empty($email) === true || empty($password) === true){
$errors[] = 'You need to enter your email and password.';
} else if(user_exists($email) === false){
$errors[] = 'Unable to find that email.';
} else {
$login = login($email, $password);
if($login === false){
$errors[] = 'Email/password combination is incorrect!';
} else {
$_SESSION['userID'] = $login;
header('Location: index.php');
exit();
}
}
}
?>
But this method will just bring me to the checkuser.php page and show me the errors there while I have to get the errors show on the form, but I seriously have no clue how to get that.
Ok, found the solution:
Here's my Jquery part:
$(document).ready(function(){
$(".bt_login").click(function(){
email = $("#email").val();
password = $("#password").val();
if(email == '' || password == ''){
$(".errors").html("Please fill in both fields!");
return false;
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: "email=" + email + "&password=" + password,
success: function(html){
if(html == 'true'){
window.location = "index.php";
} else {
$(".errors").html("Wrong username or password!");
}
}
});
return false;
});
});
and my checkuser.php:
<?php
include "core/init.php";
$email = $_POST['email'];
$password = md5($_POST['password']);
$query = "SELECT * FROM user WHERE email = '$email' AND password = '$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
$row=mysql_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['userID']=$row['userID'];
$_SESSION['last_name']=$row['last_name'];
$_SESSION['first_name']=$row['first_name'];
}
else{
echo 'false';
}
?>
Although it may not be the safest solution, it works for now :) Will try to build in more security later.

Categories