PHP-Form validation and insertion using MySql - php

I'm using this code to validate my my html form and I now need to add the form data into a table in mysql. How do I proceed I know the basics of creating a connection and sql databases but since I've already used the form's submit button i don't know how to get the data to a place where I can insert it again
<?php
// define variables and initialize with empty values
$nameErr = $passErr = $emailErr =$cpassErr="";
$name = $pass = $cpass = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$nameErr = "Enter Username";
}
else {
$name = $_POST["username"];
}
if (empty($_POST["password"])) {
$passErr = "Enter password";
}
else {
$pass = $_POST["password"];
}
if (empty($_POST["cpassword"])) {
$cpassErr = "Retype password";
}
else {
$cpass= $_POST["cpassword"];
}
if (empty($_POST["email"])) {
$emailErr = "Enter email";
}
else {
$email = $_POST["email"];
}
}
?>
<html>
<head>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table border="0" cellspacing="20">
<tbody>
<tr>
<td>Username:</td>
<td><input type="text" name="username" accept="" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" accept="" value="<?php echo htmlspecialchars($pass);?>">
<span class="error"><?php echo $passErr;?></span></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="text" name="cpassword" accept=""value="<?php echo htmlspecialchars($cpass);?>">
<span class="error"><?php echo $cpassErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" accept="" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span></td></td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Code for the connection
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="LSDB";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$u=$_POST['username'];
$p=$_POST['password'];
$e=$_POST['email'];
$ph=$_POST['phone'];
$sql="INSERT INTO register (username,password,email,phone)
VALUES
('$u','$p','$e','$ph')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>

first off i would suggest you escaping the inputs.
also worth noting you could use prepared statements and object oriented way of mysqli as most of the documents on OO are clearer than the procedural way.
like :
<?php
$u=striptags($_POST['username']);
$p=striptags($_POST['password']);
$e=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$ph=(int)$_POST['phone'];
$mysqli = new mysqli($host,$username,$password,$db_name);
$query = "INSERT INTO register (username,password,email,phone) VALUES (?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssi", $u, $p, $e, $ph);
$stmt->execute();
$mysqli->close();
?>
it would not also hurt using hash on your password like :
<?php
$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$passh = crypt($pass, '$6$'.$salt);
?>
do note that you will need to store the salt in mysql also so you can compare it later
so with these your passwords are safer and if your database gets stolen the passwords will remain hashed.

When the user submits the form, if the validation was successful, then you should execute a process function, where you can place as much instructions as you need, including storing the data in a database, or printing it in an auto-generated webpage. Everything you need.
In another order of things, looks like that code of you is too simple and hence vulnerable to cross-site scripting. You should not only validate if the fields are empty or not, but also you should use some regular expressions and the function preg_match( ) to filter which characters are entered. The best protection is to allow the user enter only the characters that are needed in each field, and not any others than those.
Example on how to handle the logic of the form:
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
// The data sent is valid, hence process it...
process_form();
}
} else {
// The form has not been sent, hence show it again...
show_form();
}

Related

Am I abusing the GOTO function here?

I am building a CRM for my wife and I to use for our business. I have created a page with several goals in mind:
Be able to create a new entry in the database.
Be able to view an existing entry in the database.
Be able to update an existing entry in the database.
I originally had several php files performing this stuff, but have now used the GOTO function to get the code to bounce around to the different parts I need run depending on what is happening all while staying on the same page.
My question is, other than it looking messy, is there a downfall to doing it this way? In the future I will be looking into other and cleaner ways to do it (suggestions are welcome), but this is working for me at the moment and I would like to move on with the project and start building the additional parts I require for the CRM. Think of this as a beta version if you will. If there is some huge drawback to what I have done already, Id rather address it now, but if this is at least mildly reasonable I will push forward.
Here is what I have:
<?php
// Include Connection Credentials
include("../../comm/com.php");
//Connection to Database
$link = mysqli_connect($servername, $username, $password, $dbname);
// Connection Error Check
if ($link->connect_errno) {
echo "Sorry, there seems to be a connection issue.";
exit;
}
// Define Empty Temporary Client ID
$new_client_id ="";
// Define Empty Success Message
$successful ="";
// Define Empty Error Messages
$firstnameErr ="";
$lastnameErr ="";
$addressErr ="";
$cityErr ="";
$stateErr ="" ;
$zipcodeErr ="";
$phoneErr ="";
$emailErr ="";
// CHECK FOR SEARCH PROCESS
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['searched'])) {
$client_id = $_POST['client_id'];
$buttontxt = "Update";
goto SearchReturnProcess;
}
}
// Retrieve Client ID
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['client_id'])) {
$buttontxt = "Create Client";
goto CreatNewClientProcess;
} else {
$client_id = $_POST['client_id'];
$buttontxt = "Update";
goto UpdateClientProcess;
}
}
// CONTINUE FOR NEW CLIENT
CreatNewClientProcess:
// Check For Missing Fields and report
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last name is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["email"])) {
$emailErr = "Email is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["address"])) {
$addressErr = "Address is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["city"])) {
$cityErr = "City is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["state"])) {
$stateErr = "State/Province is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["zipcode"])) {
$zipcodeErr = "Postal code is a required field - please make entry below";
goto FinishUpProcess;
}
}
// Prepared Statement For Database Search
if ($stmt = $link->prepare("INSERT INTO client (firstname, lastname, address, city, state, zipcode, phone, email) VALUES (?,?,?,?,?,?,?,?)")){
// Bind Search Variable
$stmt->bind_param('ssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);
// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// Execute the Statement
$stmt->execute();
}
// Close Statment
$stmt->close();
// Report Successful Entry
$successful = "Client Successfully Created!";
// Define New Client ID
$new_client_id = $link->insert_id;
// FINISH NEW CLIENT PROCESS
goto FinishUpProcess;
// CONTINUE FOR SEARCHED PROCESS
SearchReturnProcess:
// Prepared Statement For Database Search
$stmt = $link->prepare("SELECT firstname, lastname, address, city, state, zipcode, phone, email FROM client WHERE client_id=?");
// Bind Client ID into Statement
$stmt->bind_param('s', $client_id);
// Execute the Statement
$stmt->execute();
// Bind Variables to Prepared Statement
$stmt->bind_result($firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);
//fetch value
$stmt->fetch();
// Close Statment
$stmt->close();
// FINISH SEARCHED PROCESS
goto FinishUpProcess;
// CONTINUE FOR UPDATE CLIENT PROCESS
UpdateClientProcess:
// Prepared Statement For Database Search
if ($stmt = $link->prepare("UPDATE client SET firstname=?, lastname=?, address=?, city=?, state=?, zipcode=?, phone=?, email=? WHERE client_id=?")){
// Bind Search Variable
$stmt->bind_param('sssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email, $client_id);
// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$client_id = $_POST['client_id'];
// Execute the Statement
$stmt->execute();
}
// Close Statment
$stmt->close();
// Report Successful Update
$successful = "Client Updated Successfully!";
// FINISH UPDATE PROCESS
goto FinishUpProcess;
// CONTINUE FOR FINISHING UP PROCESS
FinishUpProcess:
// Disconnect from Database
mysqli_close($link)
?>
<!DOCTYPE html>
<html>
<head>
<title>Client Information</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<h4>enter client info below</h4>
<font color="red"><?php echo $successful; ?></font>
<fieldset>
<input name="client_id" value="<?php if (empty($_POST['client_id'])) { echo $new_client_id; } else { echo $_POST['client_id']; } ?>" type="hidden">
</fieldset>
<fieldset>
<font color="red"><?php echo $firstnameErr; ?></font>
<input name="firstname" value="<?php if (isset($_POST['client_id'])) { echo $firstname; } else { echo $_POST['firstname']; } ?>" placeholder="First Name" type="text" tabindex="1" autofocus>
</fieldset>
<fieldset>
<font color="red"><?php echo $lastnameErr; ?></font>
<input name="lastname" value="<?php if (isset($_POST['client_id'])) { echo $lastname; } else { echo $_POST['lastname']; } ?>" placeholder="Last Name" type="text" tabindex="2">
</fieldset>
<fieldset>
<font color="red"><?php echo $emailErr; ?></font>
<input name="email" value="<?php if (isset($_POST['client_id'])) { echo $email; } else { echo $_POST['email']; } ?>" placeholder="Email Address" type="email" tabindex="3">
</fieldset>
<fieldset>
<input name="mailinglist" id="checkbox" type="checkbox" checked>
<label>add to the mailing list</label>
</fieldset>
<fieldset>
<font color="red"><?php echo $phoneErr; ?></font>
<input name="phone" value="<?php if (isset($_POST['client_id'])) { echo $phone; } else { echo $_POST['phone']; } ?>" placeholder="Phone Number" type="tel" tabindex="4">
</fieldset>
<fieldset>
<font color="red"><?php echo $addressErr; ?></font>
<input name="address" value="<?php if (isset($_POST['client_id'])) { echo $address; } else { echo $_POST['address']; } ?>" placeholder="Street Address" type="text" tabindex="5">
</fieldset>
<fieldset>
<font color="red"><?php echo $cityErr; ?></font>
<input name="city" value="<?php if (isset($_POST['client_id'])) { echo $city; } else { echo $_POST['city']; } ?>" placeholder="City" type="text" tabindex="6">
</fieldset>
<fieldset>
<font color="red"><?php echo $stateErr; ?></font>
<input name="state" value="<?php if (isset($_POST['client_id'])) { echo $state; } else { echo $_POST['state']; } ?>" placeholder="State/Province" type="text" tabindex="7">
</fieldset>
<fieldset>
<font color="red"><?php echo $zipcodeErr; ?></font>
<input name="zipcode" value="<?php if (isset($_POST['client_id'])) { echo $zipcode; } else { echo $_POST['zipcode']; } ?>" placeholder="Postal Code" type="text" tabindex="8">
</fieldset>
<fieldset>
<font color="red"><?php echo $countryErr; ?></font>
<input name="country" value="<?php if (isset($_POST['client_id'])) { echo $country; } else { echo $_POST['country']; } ?>" placeholder="Country" type="text" tabindex="9">
</fieldset>
<fieldset>
<input name="vegan" type="checkbox">
<label>Vegan or Vegitarian</label>
</fieldset>
<fieldset>
<input name="smoker" type="checkbox">
<label>Smoker</label>
</fieldset>
<fieldset>
<textarea name="client_notes" placeholder="general notes" tabindex="10"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" data-submit="...Sending"><?php echo $buttontxt; ?></button>
</fieldset>
</form>
</div>
</body>
</html>
I'm not sure I even knew that goto existed in PHP. I've used (and abused) my share of gotos over the years, but not lately. On to the fixes:
1 - Many of your gotos (e.g., SearchReturnProcess) can be replaced with function calls. Instead of making a chunk of code starting with a label (and using goto to get there), make a separate function with the same name function SearchReturnProcess() and put the code there.
2 - For the error processing, use if elseif:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is a required field - please make entry below";
} elseif (empty($_POST["lastname"])) {
$lastnameErr = "Last name is a required field - please make entry below";
} elseif...
etc.
Then you can either make that set of statements end with an else followed by the block of "no error" code, or instead of a bunch of separate errors you can make one generic error variable (e.g., $fieldErr) and after the block have code like if ($fieldErr != '') to handle error display and simply display the errors in one location instead of next to each field.
Yes.
I won't preach about heresy and blasphemy but show you that most of your GOTOs are simply wrong.
UpdateClientProcess. That's quite strange an idea that you have to validate input for the creation only. It should be always the same for both create and update. So this one is useless and harmful
FinishUpProcess from validation routines. That's awful from the usability point of view. There was an old Chiniese torture when a victim's head was fixed under the dripping tap. Unharmful at first, it drove people crazy in time. So you are doing with your verifications. Why not to check ALL fields and then tell user at once, instead of showing them errors one by one?
FinishUpProcess from saving data. This violates the HTTP protocol rule says that after processing the POST request a server should issue a Location header redirecting a client using GET method. Otherwise if a client would refresh a page, the record will be duplicated.
It looks messy. You said that. It took me a hard time to navigate your code to review it due to its monotonous structure. Code padding was invented on purpose. In Python, for example, you are forced to use padding to distinguish subordinate code blocks.
A proper structure for this code would be like
$errors = [];
if ($_POST) {
if (empty($_POST["firstname"])) {
$errors['firstname'] = "First name is a required field - please make entry below";
}
// and so on
if (!$errors) {
if (empty($_POST['client_id'])) {
// go for insert
} else {
// go for update
}
header("Location: .");
exit;
}
$firstname = htmlspecialchars($_POST['firstname']);
// and so on
}
if (!$errors ) {
if (!empty($_GET['client_id'])) {
// search your data from a GET variable
} else {
// define empty variables
}
}
?>
<html goes here>

PHP Form Validation assistant

I really need a help. I know there are similar help with my, but have tried them out no luck.
Am creating a Registration system with user type using PHP and Mysqli procedural. Am just starting up with PHP so please bear with me.
I need help with form validation... it looks OK to me, but the error is not processing. Below is my register and errMsg code.
Connection Code:
define('HOST','localhost');
define('USERNAME','');
define('PASSWORD','');
define('DBNAME','');
$con=mysqli_connect(HOST,USERNAME,PASSWORD,DBNAME)or die('ERROR WHILE CONNECTING TO DATABASE SERVER');
?>
Registration and errMsg code
<?php
session_start();
if(is_file('include/connection.php'))
include_once('include/connection.php');
else
exit('Database FILES MISSING:(');
?>
<?php $_SESSION['main_title'] = "Registration Page"; ?>
<?php
if(isset($_SESSION['user_type'])){
header('Location: index.php');
}
if(isset($_POST['submit']))
{
extract($_POST);
// $name = $_POST["name"];
// $email = $_POST["email"];
// $password = $_POST["password"];
// $name = mysqli_real_escape_string($con, $name);
// $email = mysqli_real_escape_string($con, $email);
// $password = mysqli_real_escape_string($con, $password);
$created_at = date('Y-m-d');
$queryInsert = "insert into user (name,last_name,user_name,user_type,email,password,created_at) values ('$name','$last_name','$user_name','$user_type','$email','$password','$created_at')";
$resInsert = mysqli_query($con,$queryInsert);
if($resInsert){
$_SESSION['main_notice'] = "Successfully registered, login here!";
header('Location: index.php');
}else{
$_SESSION['main_notice'] = "Some error, try again";
header('Location: '.$_SERVER['PHP_SELF']);
}
}
?>
<?php
if(is_file('include/header.php'))
include_once('include/header.php');
?>
<?php
// define variables and set to empty values
$nameErr = $lnameErr = $userErr = "";
$name = $lname = $user = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// validate first name
if (empty($_POST["name"])) {
$nameErr = "first 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";
}
// validate last name
if (empty($_POST["lname"])) {
$lnameErr = "Last Name is required";
}else {
$lname = test_input($_POST["lname"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
// validate user type
if (empty($_POST["user_name"])) {
$userErr = "Last Name is required";
}else {
$user = test_input($_POST["user_name"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
$userErr = "Only letters and white space allowed";
}
}//end validate tag
?>
<div>
<form name="register" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return check()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" value='<?php echo $name ?>'><span style='color: red'>* <?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name" value='<?php echo $lname ?>'><span style='color: red'>* <?php echo $lnameErr;?></span></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user_name" value='<?php echo $user ?>'><span style='color: red'>* <?php echo $userErr;?></span></td>
</tr>
<tr>
<td>User Type</td>
<td>
<select name="user_type" >
<option value="member">Member</option>
<option value="leader">Leader</option>
</select>
</td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" ></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirm_password" id="confirm_password" ></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Register"></td>
</tr>
</table>
</form>
</div>
<script>
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// function check(){
// if(document.getElementById('password').value != document.getElementById('confirm_password').value ){
// alert('password not match');
// return false;
// }else{
// return true;
// }
// }
</script>
<?php
if(is_file('include/footer.php'))
include_once('include/footer.php');
?>
Am not sure if am missing something, but when i send the form without any input, it process it on database. And if i put input in just name field, it just refresh and go blank, even the value data doesn't work idea.
I hope have given enough information for your help, please if any question do ask me.
Thanks in advance
The order of your code seems like it may be the issue. You are checking if the $_POST['submit'] is set and then performing your database operations before the section of code which carries out validation. The section which sets the values to empty should come first, the you want to check if $_POST['submit'] is set, and if it is you THEN do the validation within the if statement. So quickly in pseudocode:
include PHP files
check if user is already logged in
initialise variables
if submit is set {
Validate the input
if valid {
Submit to database
} else {
return error messages as needed
}
}
I hope this helps
EDIT:
$stmt = $con->prepare("INSERT INTO user (name, last_name, user_name, user_type, email, password, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $name, $last_name, $user_name, $user_type, $email, $password, $created_at);
$stmt->execute();
$stmt->close();
$con->close();
Also, noticed a few more issues with your other code which may cause you problems.
In the input checks, you are setting variables like $nameErr if the field is invalid. Once you've sorted the code order out though you may find that you have to introduce a check for whether or not you actually have an error at the end of the validation or it will attempt to execute the database section anyway.
The error variables are echo'd to the page but if the all the inputs were acceptable, none of these variables will be defined and PHP might throw errors
Reorganise the code, and then have a careful look at it and think about how the data flow would work when valid and invalid (or null) input is provided.

Error on bindValue

I already browsed the Internet, but could not find and understand any solution provided.
Basically, I created (or rather copied some scripts from the Internet) and tried to work on the scripts to make a registration page. I'm using PHP, Mysql and XAMPP. The connection is fine already.. I tested some data inputs on a basic form etc.
but My problem is, after I messed around with the scripts, I managed to insert data into the table (peekdoordb)...all the hashing and validation form worked..except that, the form keeps submitting data into the DB even when data is wrong or the field is empty. After I messed around again, then the problem arises. The error is on " $stmt->bindValue(':name', $name);"
I keep getting this error on browser;
Notice: Undefined variable: stmt in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on
line 194
and
Fatal error: Call to a member function bindValue() on a non-object in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194
The registration.php (registration page) include 2 files which are connect.php and password.php but I never messed anything with those 2 files, because before that, data could be submitted only the problem was with the form, data keeps inserting in DB like I mentioned previously. But the main problem now is about this error.
<?php
//register.php
/**
* Start the session.
*/
session_start();
//Include password_compat library.
require 'lib/password.php';
//Include MySQL connection.
require 'connect.php';
//define variables and define to null.
$nameError = $telnoError = $usernameError = $passwordError ="";
$name = $telno = $username = $pass = "";
//Retrieve the field values from registration form.
$name = !empty($_POST ['name']) ? trim($_POST['name']) : null ;
$telno = !empty ($_POST ['telno']) ? trim($_POST['telno']) : null;
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true; // Boolean - Set to true b4 validating
//If the POST var "register" exists ( the submit button), then I can
//assume that the user has submitted the registration form.
if(isset($_POST['register'])){
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
if (empty($_POST["name"])) {
$nameError = "Name is required";
}else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["telno"])) {
$telnoError = "Tel number is required";
} else {
$telno = test_input($_POST["telno"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/^[a-zA-Z ]*$/",$telno)) {
$telnoError = "Invalid tel no format";
}
}
if (empty($_POST["username"])) {
$usernameError = "username is required";
} else {
$username = test_input($_POST["username"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameError = "Only letters and email syntax required";
}
}
if (empty($_POST["password"])) {
$passwordError = "passworde is required";
} else {
$pass = test_input($_POST["password"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/",$pass)) {
$passwordError = "Only password letter syntax";
}
}
//*******************************************************************
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if($row['num'] > 0){
die('That username already exists!');
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
}
//If the signup process is successful.
elseif($formValid){
//******************************ppppp
//Bind our variables.
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
$stmt = $pdo->prepare($sql);
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
//Execute the statement and insert the new account.
$result = $stmt->execute();
//What you do here is up to you!
echo 'Thank you for registering with our website.';
}
else {
die('something wrong!');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<style type="text/css">
.lucida {
font-family: "MS Serif", "New York", serif;
}
body form table {
font-weight: bold;
}
</style>
</head>
<body>
<h1> </h1>
<h1> </h1>
<h1 align="center"> Register</h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div align="center">
<table width="800" border="0">
<tr>
<td width="404" class="lucida"><div align="right">Name :</div></td>
<td width="386"><input class="input" name="name" type="text" value="<?PHP print $name ; ?>">
<span class="error">* <?php echo $nameError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Contact Number :</div></td>
<td><input class="input" name="telno" type="text" value="<?PHP print $telno ; ?>">
<span class="error">* <?php echo $telnoError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Email (Username) :</div></td>
<td><input class="input" name="username" type="text" value="<?PHP print $username ; ?>">
<span class="error">* <?php echo $usernameError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Password :</div></td>
<td><input class="input" name="password" type="text" value="">
<span class="error">* <?php echo $passwordError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
</table>
<input type="submit" name="register" value="Register">
<br>
</div>
</button>
</form>
</body>
</html>
the form keeps submitting data into the DB even when data is wrong or the field is empty
You are checking $formValid in the wrong place. Your conditions can be summarized as follows:
$formValid = true;
if (isset($_POST['register'])) {
} else if ($formValid) {
} else { ...
As above, if $_POST['register'] is not set (e.g. when loading the registration form) your code will execute whatever is in the second if statement. Your condition structure should be amended to include the form validity check inside the first condition:
$formValid = true;
if (isset($_POST['register'])) {
// validation stuff goes here
if ($formValid) {
//database insert goes here
}
else {
//invalid data. Tell the user
}
}
Also as a rule, you should assume any data from the user is invalid unless proven otherwise i.e. $formValid should be false initially.
Notice: Undefined variable: stmt in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 19
Fatal error: Call to a member function bindValue() on a non-object in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194
You are trying to use a variable $stmt that has not been defined within the scope of else if($formValid). The same goes for $sql. Any variable must be set before it is used. The order should be:
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
Try this -
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
//Execute the statement and insert the new account.
$stmt->execute();
You have bindValue before prepare your statement so you are getting this error. Can prepare your statement below your $sql variable then bind your value. This is working for me.
UPDATED ANSWER
<?php
//register.php
/**
* Start the session.
*/
session_start();
//Include password_compat library.
require 'lib/password.php';
//Include MySQL connection.
require 'connect.php';
//define variables and define to null.
$nameError = $telnoError = $usernameError = $passwordError = "";
$name = $telno = $username = $pass = "";
//Retrieve the field values from registration form.
$name = !empty($_POST ['name']) ? trim($_POST['name']) : null;
$telno = !empty($_POST ['telno']) ? trim($_POST['telno']) : null;
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true; // Boolean - Set to true b4 validating
//If the POST var "register" exists ( the submit button), then I can
//assume that the user has submitted the registration form.
if (isset($_POST['register'])) {
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
if (empty($_POST["name"])) {
$nameError = "Name is required";
$formValid = false;
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameError = "Only letters and white space allowed";
$formValid = false;
}
}
if (empty($_POST["telno"])) {
$telnoError = "Tel number is required";
$formValid = false;
} else {
$telno = test_input($_POST["telno"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/^[a-zA-Z ]*$/", $telno)) {
$telnoError = "Invalid tel no format";
$formValid = false;
}
}
if (empty($_POST["username"])) {
$usernameError = "username is required";
$formValid = false;
} else {
$username = test_input($_POST["username"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameError = "Only letters and email syntax required";
$formValid = false;
}
}
if (empty($_POST["password"])) {
$passwordError = "passworde is required";
$formValid = false;
} else {
$pass = test_input($_POST["password"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/", $pass)) {
$passwordError = "Only password letter syntax";
$formValid = false;
}
}
//*******************************************************************
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if ($row['num'] > 0) {
$usernameError = 'That username already exists!';
$formValid = false;
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
//$passwordHash = $pass;
if ($formValid) {
//******************************ppppp
//Bind our variables.
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
//Execute the statement and insert the new account.
$result = $stmt->execute();
//What you do here is up to you!
echo 'Thank you for registering with our website.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<style type="text/css">
.lucida {
font-family: "MS Serif", "New York", serif;
}
body form table {
font-weight: bold;
}
</style>
</head>
<body>
<h1> </h1>
<h1> </h1>
<h1 align="center"> Register</h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div align="center">
<table width="800" border="0">
<tr>
<td width="404" class="lucida"><div align="right">Name :</div></td>
<td width="386"><input class="input" name="name" type="text" value="<?PHP print $name; ?>">
<span class="error">* <?php echo $nameError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Contact Number :</div></td>
<td><input class="input" name="telno" type="text" value="<?PHP print $telno; ?>">
<span class="error">* <?php echo $telnoError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Email (Username) :</div></td>
<td><input class="input" name="username" type="text" value="<?PHP print $username; ?>">
<span class="error">* <?php echo $usernameError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Password :</div></td>
<td><input class="input" name="password" type="text" value="">
<span class="error">* <?php echo $passwordError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
</table>
<input type="submit" name="register" value="Register">
<br>
</div>
</button>
</form>
</body>
</html>

Are the variables in this code properly escaped?

I think I have properly escaped everything, but yet I'm wondering whether I did the right thing. I remember to read somewhere that we shouldn't filter the input, just the output. In my case, does it mean that I shouldn't use the function sanitize anywhere? And just stick to prepare statements and htmlscpecialchars?
<?php
#Connection to the database
function dbcon (){
try{
$db = new PDO('mysql:dbname=php_test;host=localhost','root','mysql');
}
catch (PDOException $e){
echo $e->getMessage();
exit();
}
return $db;
}
#Sanitize the input for preventing hacking attempts
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
#Get the list of countries from the DB
function getCountries() {
$db = dbcon();
$query = "SELECT country FROM countries";
$stmt = $db->prepare($query);
$stmt->execute();
$countries = "";
while ($row = $stmt->fetch()) {
$countries .= '<option value= "'.$row['country'].'">'.$row['country'].'</option>';
}
return $countries;
}
$name = $email = $password = $password2 = $country = "";
$validForm = True;
#If it's a submission, validate the form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$db = dbcon();
#Name validation
$name = sanitize($_POST["name"]);
if ((strlen($name) < 2) || (strlen($name) > 50)) {
echo "<span style=\"color: #FF0000;\"> Name must have between 2 and 50 characters </span> <br>";
$name = "";
$validForm = False;
}
#Email validation
$email = sanitize($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span style=\"color: #FF0000;\"> Check the format of the email </span> <br>";
$email = "";
$validForm = False;
}
else { #If it's a valid email, check whether or not it's already registered
$query = "SELECT email FROM users;";
$stmt = $db->prepare($query);
$stmt->execute();
$found = False;
while (($row = $stmt->fetch()) and (!$found)) {
if ($row["email"] == $email) {
$found = True;
}
}
if ($found) {
echo "<span style=\"color: #FF0000;\"> This email is already registered </span> <br>";
$email = "";
$validForm = False;
}
}
#Password validation
$password = sanitize($_POST["pass1"]);
if ((strlen($password) < 6) || (strlen($password) > 20)) {
echo "<span style=\"color: #FF0000;\"> Password must have between 6 and 20 characters </span> <br>";
$validForm = False;
}
else { #If it's a valid password, check whether or not both passwords match
$password2 = sanitize($_POST["pass2"]);
if ($password != $password2) {
echo "<span style=\"color: #FF0000;\"> Passwords don't match </span> <br>";
$validForm = False;
}
#If passwords match, hash the password
else {
$password = password_hash($password, PASSWORD_DEFAULT);
}
}
#We don't need to validate country because it's retrieved from the DB, but we sanitize it just in case a hacker modified the POST using a proxy
$country = sanitize($_POST["country"]);
#All checks done, insert into DB and move to success.php
if ($validForm) {
$query = "INSERT INTO users VALUES(:name, :email, :password, :country);";
$stmt = $db->prepare($query);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':country', $country);
$stmt->execute();
header("Location: success.php");
}
}
?>
<html>
<head>
</head>
<body>
<!-- Submitting to this very file -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table>
<tr> <!-- Name -->
<td><label for="name">Name:</label></td>
<td><input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>" required /></td>
<td><span style="color: #FF0000;">*</span></td>
<td>Between 2 and 50 characters</td>
</tr>
<tr> <!-- Email -->
<td><label for="email">Email:</label></td>
<td><input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>" required/></td>
<td><span style="color: #FF0000;">*</span></td>
<td>Must be a valid address</td>
</tr>
<tr> <!-- Password -->
<td><label for="pass1">Password:</label></td>
<td><input type="password" name="pass1" required/></td>
<td><span style="color: #FF0000;">*</span> </td>
<td>Between 6 and 20 characters</td>
</tr>
<tr> <!-- Confirm password -->
<td><label for="pass2">Confirm password:</label></td>
<td><input type="password" name="pass2" required/></td>
<td><span style="color: #FF0000;">*</span></td>
<td>Must be the same as the password</td>
</tr>
<tr> <!-- Country -->
<td><label for="country">Country:</label></td>
<td><select name="country"> <?php echo getCountries(); ?></select></td>
<td><span style="color: #FF0000;">*</span></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Its all done with PDO::prepare
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
and there is anther alternate
PDO::quote
PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.
To know about XSS Injection Read this Answer too
One thing I always use when cleaning data entered by the user is to use strip_tags()...
Specially if the content is to be echoed at some point... you dont want to make easy to inject scripts using your forms.
Try to type <script>alert("hello");</scirpt> in one of the text element and submit...

inserting data into mysql from an html textboxes. using php/mysql

I can't see where i am going wrong, it just won't let me connect to the mysql database and i only get error message when trying to save details.?????? i think there may be a problem where it shows $sql for inserting the values into the table. the first part newstudent.php works, but sql.php does not work.
//new student.php
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
//sql.php
$conn=mysql_connect("localhost", "20915184", "mysqluser");
mysql_select_db("db5_20915184", $conn);
// If the form has been submitted
$id=$_POST['txtstudentid'];
$password=$_POST['txtpassword'];
$dob=$_POST['txtdob'];
$firstname=$_POST['txtfirstname'];
$lastname=$_POST['txtlastname'];
$house=$_POST['txthouse'];
$town=$_POST['txttown'];
$county=$_POST['txtcounty'];
$country=$_POST['txtcountry'];
$postcode=$_POST['txtpostcode'];
// Build an sql statment to add the student details
$sql="INSERT INTO student
(studentid,password,dob,firstname,lastname,house,town,county,country,postcode) VALUES
('$id','$password','$dob','$firstname','$lastname','$house','$town','$county','$country','$postcode')";
$result = mysql_query($sql,$conn);
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The username comes before the password in mysql_connect();
Try running the sql statement in phpmyadmin and see if it works there!
With in your if else statement, where you echo "ERROR", try printing mysql_error() this would show that your mysql_connect() is wrong If the username/password combo is wrong.
To clean this up a bit, Here is what the if/else should look like
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
} else {
echo "There has been an error <br/>";
print mysql_error();
}
EDIT :
Also, Prevent sql injection with mysql_real_escape_string() on all posted values
Well your code is incomplete, you must insert when the button is clicked also its important to check if a field isset before saving the field in the database also important to filter and sanitize user inputs before submitting. Learn to use prepared statements, with mysqli prepared or PDO whatever works for you, Also don't store passwords in plain text/md5 use password_hash() and password_verify()
Your code with mysqli prepared should look like :
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
sql.php
<?php
$servername = "localhost";
$username = "20915184";
$password = "mysqluser";
$dbname = "db5_20915184";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errors = "";
if (isset($_POST['submit'])) { // submit button clicked
// validate fields
if (empty($_POST['txtstudentid'])) {
echo "enter id";
$errors++;
} else {
$id = userData($_POST['txtstudentid']);
}
if (empty($_POST['txtpassword'])) {
echo "enter password";
$errors++;
} else {
$password = userData($_POST['txtpassword']);
$hash = password_hash($password, PASSWORD_DEFAULT); //hashing password
}
if (empty($_POST['txtdob'])) {
echo "enter date of birth";
$errors++;
} else {
$dob = userData($_POST['txtdob']);
}
if (empty($_POST['txtfirstname'])) {
echo "enter first name";
$errors++;
} else {
$firstname = userData($_POST['txtfirstname']);
}
if (empty($_POST['txtlastname'])) {
echo "enter last name";
$errors++;
} else {
$lastname = userData($_POST['txtlastname']);
}
if (empty($_POST['txthouse'])) {
echo "enter house";
$errors++;
} else {
$house = userData($_POST['txthouse']);
}
if (empty($_POST['txttown'])) {
echo "enter town";
$errors++;
} else {
$town = userData($_POST['txttown']);
}
if (empty($_POST['txtcounty'])) {
echo "enter country";
$errors++;
} else {
$country = userData($_POST['txtcounty']);
}
if (empty($_POST['txtpostcode'])) {
echo "enter post code";
$errors++;
} else {
$postcode = userData($_POST['txtpostcode']);
}
if ($errors <= 0) { //all fields are set no errors
//start query
//check if user id does not exist
$statement = $conn->prepare("SELECT studentid FROM students WHERE studentid = ?");
$statement->bind_param('s', $id);
$statment->execute();
$statement->bind_result($studentID);
if ($statement->num_rows == 1) {
echo "the student Id " . $studentID . " already registered please login";
} else {
// no results then lets insert
$stmt = $conn->prepare("INSERT INTO students (studentid,password,dob,firstname,lastname,house,town,country,postcode) VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssss", $id, $hash, $dob, $firstname, $lastname, $house, $town, $country, $postcode);
$stmt->execute();
echo "<p>Your Details have been updated<br> <a href=\"Home.html\">Back to main page";
$stmt->close();
$conn->close();
}
}
}
//filter userinput
function userData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
There are many good tutorials on the net on this, hopes this will help, I'm also open to suggestions and corrections incase I missed something.
**> Question mark (?)(placeholder) is used to assign the value.In Prepared
Statements we assign in the values in bind parameter function so that
our query is processed in secure way and prevent from SQL injections.**
In Prepared Statements we pass or attach the values to database query with the help of Bind Parameter function.
You have to attach all the variables whose value you want in your query with their appropriate Data Types just like we pass the 's' means the variable contains a string Data Type.
To execute the query in Prepared Statements you have to use execute() function with query object.
Remove the parameter from your with the inside inside and put in an empty string. i.e
VALUES('','$password','$dob',
etc etc

Categories