Form and SQL Validation using PHP - php

When user clicks on the Save, check whether the data is successfully inserted record to the table, and display a proper message accordingly. If forms are empty then the error message should be shown and database should not have any record.
//SAVE
if (isset($_POST['SAVE'])) {
$Name = $_POST['name'];
$City = $_POST['city'];
$query = "Insert Into Info Values('$Name','$City')";
$result = mysqli_query($con, $query) or die ("query is failed" . mysqli_error($con));
$Name = '';
$City = '';
if(mysqli_affected_rows($con)>0) {
echo "record is saved";
}else {
echo "record is not saved";
}
I can only do validation through php. I am not sure if I am doing this right. So far I can get the "record is saved" message on my form, but I cannot get the latter if the form are empty. It just make an empty record in my database.

Untested Code:
if (!isset($_POST['SAVE'], $_POST['name'], $_POST['city'])) { // avoid Notices
echo "Missing required submission data";
} elseif (!strlen(trim($_POST['name']))) { // validate however you wish
echo "Name data is not valid"; // explain however you wish
} elseif (!strlen(trim($_POST['city']))) { // validate however you wish
echo "City data is not valid"; // explain however you wish
} elseif (!$con = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $con->connect_error <-- never show actual error details to public
} elseif (!$stmt = $con->prepare("INSERT INTO Info VALUES (?,?)")) {
echo "Error # prepare"; // $con->error; // don't show to public
} elseif (!$stmt->bind_param("ss", $_POST['name'], $_POST['city'])) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
echo "Error # execute"; // $stmt->error; // don't show to public
} else {
echo "Insert Successful";
}
The validation conditions on the submission data ensure that the values are not empty and they are not completely comprised of whitespace characters. If you wish to refine the validation requirement further, just update the conditions.
If you want to simply ensure that $_POST['name'] and $_POST['city'] are not empty, you can replace the first three conditionals with
if (empty($_POST['SAVE']) || empty($_POST['name']) || empty($_POST['city'])) {
echo "Submission data is missing/invalid";
}...
If you don't use a prepared statement, then name values like Paul O'Malley will break your query. Worse, if someone wants to try to run some injection attacks, your query is vulnerable.
Checking affected_rows() is unnecessary. If there is no error message from the query execution, the INSERT query was a success.
The above suggestions are all best practices which I urge you to adopt.

Checking isset($_POST['SAVE']) only tells you if "SAVE" is set. It does not tell you if the fields have values.
To do the validation in PHP, use something like the following:
if (isset($_POST['SAVE'])) {
$Name = $_POST['name'];
$City = $_POST['city'];
if ($Name && $City)
{
//...
//code to insert data into the database goes here
//...
if(mysqli_affected_rows($con)>0) {
echo "record is saved";
}else {
echo "record is not saved (error saving)";
}
} else {
echo "record is not saved (input was empty)";
}
}
The key being the if ($Name && $City) check.
Alternately, if you want to rely on mysql to reject the insert on blank values, then make sure the fields in the mySql table are not nullable and then change this part of your code: (but this would be moving the validation to MySql)
$Name = $_POST['name']?$_POST['name']:null;
$City = $_POST['city']?$_POST['city']:null;

Related

I can't seem to get this else statement to work in php

<?php
session_start();
$link = mysqli_connect(database connection info);
if (mysqli_connect_error()) {
echo "Could not connect to database";
die;
}
if (isset($_POST['submit'])) {
$query = "SELECT * FROM users WHERE email = '".$_POST['email']."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($_POST['email'] == $row['email'] && password_verify($_POST['password'], $row['password']))
{
$success .= "We're in baby";
} else {
$error .= "didn't work boi";
}
}
}
?>
Basically for some reason the else statement in this code
if ($_POST['email'] == $row['email'] && password_verify($_POST['password'], $row['password']))
{
$success .= "We're in baby";
} else {
$error .= "send help";
}
is not working at all. The problem isn't within the error variable as echo does not work either. I can't get the else statement to output any response whatsoever if the original if statement returns false. The if statement executes perfectly fine if it returns true!
Please help.
As per my comment, to get the else statement executed, enter a valid email address from your database and a wrong password. That should get to the else statement.
To echo $error, define $error = ''; at the top of the script and then add
echo $error; //Below the closing `}` of the `if($row....) ` statement
Also your query is not safe at all. You're directly injecting a variable that can be easily manipulated by anyone. You should never trust such. Hence why we have prepared statements. They help prevent SQL injection attacks as well as those pesky quoting issues. Visit the link below for a tutorial on how to use them with the mysqli_ API.
https://phpdelusions.net/mysqli
Add an else part for the if ($row = mysqli_fetch_array($result)) - perhaps your query fails or the specified email doesn't exist in the db.
The condition $_POST['email'] == $row['email'] is useless as it's already part of the SQL statement.
Also, important(!): your code is vulnerable to SQL injection. Do not put unescaped values from POST to an SQL query.

PHP - Form error alerts displays on page load

i am a newbee and just learning along the way. I have two forms on a page (I have only shown one of them as the other form is the same code with different variables). Both their error messages display on page load. How can I stop this?
I have read multiple posts regarding this but I still cannot find a solution.
<?php
if(isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
// Save $_POST to $_SESSION
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$stmt = mysqli_prepare($dbc, $insert_det);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}
} else {
echo "<b>Oops! we have an issu </b>";
}
?>
You have an else after your if (isset($_POST['Update'])). Inside that else you are displaying errors as if the user tried to submit the form. $_POST['Update'] will only be set if the user tried to submit the form. Move that else inside your if:
if (isset($_POST['Update'])) {
/* a bunch of code to insert into the DB */
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}else{
echo "<b>Oops! we have an issu </b>";
}
}
In Addition:
The commenter is right. You are at risk for SQL Injection. Please use prepared statements instead.
The problem is your else statement is running every time the variable $_POST['Update'] is not set.
One way to fix this is to move your error message inside your form checking code. Something like this would work:
if (isset($_POST['Update'])) {
/* unchanged code snipped */
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
Hope that helps!

PHP If statement returning early(amateur)

I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";

A text form field needs to be required

I've been struggling to have a text form field required. So when some one doesn't fill his name he will receive an error like 'No title filled!'
I got this now but it doesn't work that well cause when I submit it insert into the db.
if(isset($_POST['submit'])) {
$update = "UPDATE post SET `title`='$_POST[title]', `pic`='$_POST[pic]', `youtube`='$_POST[youtube]' WHERE id = $_POST[id]";
$db->query($update) or die($db->error);
if($_POST['title'] == "") {
$error = "Title is required!";
}
if ($_POST['pic'] == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
echo '<p>Your post has been updated!</p>';
}
}
You need to stop your code from being executed if an error is found, not just echo the error. All your other code that submits the data to the database should ONLY be executed if there is no error. Try something like this:
Edit: Upon seeing the update to your code, this is what you need to do:
if(isset($_POST['submit'])) {
if(!isset($_POST['title']) || trim($_POST['title']) == "") {
$error = "Title is required!";
}
if (!isset($_POST['pic']) || trim($_POST['pic']) == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
$update = "UPDATE post SET `title`='" . mysql_real_escape_string($_POST['title']) . "', `pic`='" . mysql_real_escape_string($_POST['pic']) ."', `youtube`='" . mysql_real_escape_string($_POST['youtube']) ."' WHERE id = " . mysql_real_escape_string($_POST['id']);
$db->query($update) or die($db->error);
echo '<p>Your post has been updated!</p>';
}
}
The problem is, your data was being submitted to the database no matter what happened after with the validation - by the time you checked for errors it was too late, as the SQL had already been executed.
If you do it the way shown above, it will only submit if the $error variable is not set, which is what you want.
I wouldn't just rely on
if($_POST['title'] == "")
because it will not work if someone enters a space into the text field. For one thing, a title shouldn't be too long? So you can set a max-length for it?
Also maybe run a few more checks such as:
I wouldn't just rely on
if(!isset($_POST['title'] || $_POST['title'] == "" || $_POST['title'] == " ")
{
// Error
}
else
{
// Database query
}
You want the else, otherwise it will always execute the database query, whether or not they haven't filled out the form properly.

Validating user input using php

I'm new to php and mysql and I'm trying to check if a user has entered something into a a coupls of textboxes and to also check if what has been entered is string. I want to do a check before posting to the database. I also want the html form to retain the value initially entered by the user. Please how do i achieve this.
Here's what I've done so far. This works but it still shows that the data has been entered successfully.
if(isset($_POST['register'])){
//PHP FIELD VALIDATIONS
if($_POST['fname']==""){
echo "First name is required <br/>";
}
else{
$fname= filter_var($_POST['fname'], FILTER_SANITIZE_STRING);
}
if($_POST['lname']==""){
echo "Last name is required <br/>";
}
else{
$lname= $_POST['lname'];
}
if($_POST['email']==""){
echo "Email address is required <br/>";
}
else{
$email= $_POST['email'];
}
if($_POST['pword']==""){
echo "Password is required<br/>";
}
else{
$pword= $_POST['pword'];
}
$fname=mysql_real_escape_string($fname);
$lname=mysql_real_escape_string($lname);
$email=mysql_real_escape_string($email);
$pword=mysql_real_escape_string($pword);
require_once 'scripts/connect_to_mysql.php';
$sql = "INSERT INTO customer ".
"(First_name,Last_name, Email, Password, date_added) ".
"VALUES('$fname','$lname','$email','$pword', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not enter data: ' . mysql_error());
}
echo "<span style='color:green;'>Entered data successfully</span>";
mysql_close($conn);
}
?>
Firstly and most importantly, you should change from mysql to either mysqli or PDO.
Secondly, to ensure all fields are entered before submitting, you could loop through the inputs, checking each if they are empty, and running any input specific checks you wish. i.e checking if an input is a string you can do is_string($variable).
If any of the checks fail, set a variable e.g. $failedValidation, then wrap your sql execution code in an if statement - if $failedValidation !isset, or is set to false, however you want to handle it - then run the code.
Instead of using $fname=mysql_real_escape_string($fname); use $fname = htmlspecialchars($fname);.
Looping through $_POST array:
$Validated = True; // Validated needs to be set to true, for the SQL code to run
// Loop through all variables stored in the $_POST array
foreach($_POST as $value)
{
if(empty($value)) // If any of the $_POST variables are empty, set $Validated to false
{
$Validated = False;
}
}
// If none of the fields were empty, $Validated will have remained true after our loop
if($Validated == True) {
// Run SQL code
}
Hopefully I've explained it in a way you can understand, and I hope it helps you.
Form Validation:
You'll need a mechanism that validates fields in your form and echos some validation error. The way you write php is pretty outdated, today php application usually use a pattern like MVC for the separation of concerns. Read about both, MVC and SoC.
However, the most simple solution here would be a validation class:
class Validator {
public static function email($postField, $message) {
if (isset($_POST[$postField]) {
// Example of full email validation here https://github.com/cakephp/cakephp/blob/master/lib/Cake/Utility/Validation.php#L437
$regex = '...';
if (!preg_match($regex, $email)) {
return $message;
}
}
}
public static function notEmpty($postField, $message) {
if (isset($_POST[$postField]) && empty($_POST[$postField])) {
return $message;
}
}
public static function multi($field, $rules = array()) {
foreach ($rules as $rule => $message) {
echo Validator::{$rule}($field, $message);
}
}
}
echo Validator::email('email', 'Your email address is wrong!');
Validator::multi('email', array('email' => '...', 'notEmpty' => '...'));
This is a very basic example but you get the idea. This could be extended and improved a lot to automate it much more.
Honestly I'm not in the mood to write a complete article about that right now because I guess there are plenty of them already, just try to Google for server side form validation in the context of php.
Database:
You're using the as deprecated flagged mysql_* functions, don't use them, use mysqli or PDO instead.
There is a big warning for these functions on each documentation page:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.
For how you properly use and escape SQL queries see this: How can I prevent SQL injection in PHP?
PDO example.
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Use below code:
if(isset($_POST['register'])){
//PHP FIELD VALIDATIONS
$validated = true;
if($_POST['fname']==""){
echo "First name is required <br/>";
$validated = false;
}
else{
$fname= filter_var($_POST['fname'], FILTER_SANITIZE_STRING);
}
if($_POST['lname']==""){
echo "Last name is required <br/>";
$validated = false;
}
else{
$lname= $_POST['lname'];
}
if($_POST['email']==""){
echo "Email address is required <br/>";
$validated = false;
}
else{
$email= $_POST['email'];
}
if($_POST['pword']==""){
echo "Password is required<br/>";
$validated = false;
}
else{
$pword= $_POST['pword'];
}
if ($validated) {
$fname=mysql_real_escape_string($fname);
$lname=mysql_real_escape_string($lname);
$email=mysql_real_escape_string($email);
$pword=mysql_real_escape_string($pword);
require_once 'scripts/connect_to_mysql.php';
$sql = "INSERT INTO customer ".
"(First_name,Last_name, Email, Password, date_added) ".
"VALUES('$fname','$lname','$email','$pword', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not enter data: ' . mysql_error());
}
echo "<span style='color:green;'>Entered data successfully</span>";
mysql_close($conn);
}
}

Categories