Empty fields can get inserted into my database - php

I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?

The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong

Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.

Related

How do I make a function to validate the input of the user and link it to my CRUD php file?

I tried learning Regex. Now, I am trying to create a function to validate the user inputs but unsure how to implement to PHP. Please help
**This is my Validation php**
<?php
function validateInput($userID, $userName, $userContact, $userEmail, $userDOB)
{
if(!preg_match("/^[a-zA-Z0-9]{1-10}$/", $userID)) //checks for userID
{
echo "Only Numbers and letters allowed in ID Field";
}
else if(!preg_match("/^[a-zA-z\s]{1-10}$/", $userName)) //checks for User Name
{
echo "Only letters and spaces allowed in Name Field";
}
else if(!preg_match("/^[0-9]{8}$/", $userContact)) //checks for User Contact
{
echo "Only numbers allowed in Contact Field";
}
else if(!preg_match("/\w+#\w+.\w+/", $userEmail)) //checks for User Email
{
echo "Invalid Email Format";
}
else if(!preg_match("/^\d{2}-\d{2}-\d{4}$/", $userDOB)){ //checks for user Date of Birth
echo"Invalid Date Format";
}
}
**This is the CRUD.php file. I want to link it the validation.php function here. How do I do it?
<?php
$con = mysqli_connect("localhost", "root", "", "db5c3af"); if (!$con) {
die('Could not connect: ' . mysqli_connect_errno()); } include "q4.php";
$actiontype = $_POST["actiontype"]; $add = $actiontype === "Add"; //boolean type comparator to check actiontype value === checks value + type $update = $actiontype === "Update"; $delete = $actiontype === "Delete";
The problem lies here but I am unsure how to do.
if($actiontype!= "List All"){
$userID = $_POST["userID"];
$userName = $_POST["userName"];
$userContact = $_POST["userContact"];
$userEmail = $_POST["userEmail"];
$userDOB = $_POST["userDOB"];
$check = validateInput($userID, $userName, $userContact, $userEmail, $userDOB);
if($check==false){
;
} }
if ($add || $update || $delete) { //Read in the form data assign to variables
$userID = $_POST["userID"];
$userName = $_POST["userName"];
$userContact = $_POST["userContact"];
$userEmail = $_POST["userEmail"];
$userDOB = $_POST["userDOB"];
if ($add) {
$query = $con->prepare("Insert into ItemA4491209 VALUES(?,?,?,?,?)");
$query->bind_param('ssiss', $userID, $userName, $userContact, $userEmail, $userDOB);
}
$con->close();

Check if user exists Registration

I am building a social app in Corona SDK with PHP being the back-end.
I am trying to sign up to the app but a block of code is getting skipped over.
if (!$errors) {
$stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
foreach (['username', 'email'] as $field) {
if ($row[$field] == $_POST[$field]) {
echo "Sorry, that " . $field . " is already in use.";
die();
}
}
}
}
That code checks if the username or email that was entered is already in the DB. It works fine with my website but it doesn't work with the app. I commented out all of the other echo statements and verified that that specific block of code just doesn't run. Can someone help me ?
/*if ($_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {
// Use full absolute URL header('Location: https://www.yoursite.com/index.php');
//header('Location: index.php');
echo "Not POST";
die();
} */
require 'config/connect.php';
$con = new mysqli(...$dbCredentials);
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$pw = $_POST['pw'] ?? '';
$errors = [];
if (!trim($username)) {
echo 'Fill in username to sign up';
die();
}
if (!preg_match("/^[a-zA-Z0-9]{5,}$/", $username)) {
echo 'Invalid username, only letters and/or digits.';
die();
}
if (!trim($pw)) {
echo 'Fill in password to sign up';
die();
}
if (!trim($email)) {
echo 'Fill in email to sign up';
die();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email';
die();
}
if (!$errors) {
$stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
foreach (['username', 'email'] as $field) {
if ($row[$field] == $_POST[$field]) {
echo "Sorry, that " . $field . " is already in use.";
die();
}
}
}
}
$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
if (!$errors) {
$pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, ['cost' => 14]);
$stmt = $con->prepare("INSERT INTO users (username, email, pw, ip_address)
VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $email, $pw, $ipAddress);
$stmt->execute();
$_SESSION["user_id"] = $_POST['username'];
echo "success";
die();
} else {
echo 'something is wrong here.';
die();
}
$_SESSION['error'] = '<b><p style="color: #fff; font-size: 30px; top: 34%;right: 50%;position: absolute;">
' . $errors . '</p></b>';
//header('Location: index.php');
//exit();
You should the early returns concept. First check if there are errors, show error message and exit. If there are no errors then move ahead further to the desired case. This may help.
if ($errors) {
echo 'something is wrong here.';
die();
}
Too complicated! I would simplified that like:
SELECT COUNT(`username`) FROM `users` WHERE username=? OR email=?;
$stmt->bind_param("ss", $username, $email);
In PDO there is a function called fetchColumn() to get the count as int. Its either 0 or 1. There should be a similar function in mysqli. I think it's mysqli_fetch_field()
username, password and email can simplified as well:
if (empty(trim($username)) or !ctype_alnum($username))
{ die('Username is either empty or invalid! Only alphanumeric characters'); }
if (empty(trim($pw)))
{ die('Fill in password to sign up'); }
if (empty(trim($email)) or !filter_var($email, FILTER_VALIDATE_EMAIL))
{ die('Email is either empty or not a valid address!'); }
if (!$errors) { can't be false
$pw = password_hash($pw);
never store username in session always user id its way safer!
If this should not work try to place an var_dump($errors) before sql check.
If this should not work check database connection and bind params values

How to stop mysqli_query from adding records with missing info?

I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
$emailErr = ''; //it is a good practice to initialize variable before its use.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {
//insert it to the db.
//THIS IS INSECURE WAY - Check links in comments!
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
header('location: index.php');
exit();

How to debug a mistake when inserting data into the table?

PHP code didn't insert.
<?php
$message = " ";
require "database.php";
if (isset($_POST["submit"])) {
if (empty($_POST["email"]) || empty($_POST["password"])) {
$message = "Email or Password is Incorrect";
} else {
$email = '$_POST[email]';
$pass = '$_POST[password]';
if ($email && $pass) {
$db = mysqli_select_db($conn, "auth");
$sqli = "INSERT INTO users (email, password) VALUES($email, $pass)";
if (mysqli_query($conn, $sqli)) {
$message = "New record created successfully";
} else {
$message = "Cannot create user!";
}
}
}
}
?>
$conn = mysqli_conncect("localhost","root","","auth");
I tried everything but not found the mistake to insert the query into the table.
Remove the single quotation in your else statement. PHP will interpret it as a string instead of a POST variable.
That is:
$email = $_POST['email'];
$pass = $_POST['password'];

PHP Form to SQL Error

I am trying to write from form to my SQL database. This is all local through WAMP, if that makes a difference.
The error I am receiving is as follows:
Error: INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address) VALUES ('Dominic', '123 Fake Street', 'Dom's Business Name', '', 'Dominic', 'Fichera', 0123456789', '0123456789', '')
Erreur de syntaxe pr�s de 's Business Name', '', 'Dominic', 'Fichera', 0123456789', '0123456789', '')' � la ligne 2
I've also uploaded an image here: http://s7.postimg.org/ecqci36nv/error_snippet.png
I am unsure if this error refers to an issue within my code, an issue with the way I've setup my SQL table or something completely different.
Here is the main chunk of my code where all of the action happens:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yard"])) {
$yard_error = "Yard is required";
} else {
$yard = test_input($_POST["yard"]);
}
if (empty($_POST["full_address"])) {
$full_address_error = "Address is required";
} else {
$full_address = test_input($_POST["full_address"]);
}
if (empty($_POST["first_name"])) {
$first_name_error = "First name is required";
} else {
$first_name = test_input($_POST["first_name"]);
}
if (empty($_POST["last_name"])) {
$last_name_error = "Last name is required";
} else {
$last_name = test_input($_POST["last_name"]);
}
if ($_POST["business_status"] = "") {
$business_status_error = "Business status is required";
} else {
$business_status = test_input($_POST["business_status"]);
}
$business_name = $_POST["business_name"];
$landline_number = $_POST["landline_number"];
$mobile_number = $_POST["mobile_number"];
$email_address = $_POST["email_address"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address)
VALUES ('$yard', '$full_address', '$business_name', '$business_status', '$first_name', '$last_name', $landline_number', '$mobile_number', '$business_status')";
if ($conn->query($sql) === TRUE) {
$yard_confirmation = $yard . "successfully saved.";
} else {
$yard_confirmation = "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I would recommend something like this:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
And:
$errors = array();
($_POST["business_name"]) ? $business_name = test_input($_POST["business_name"]) : $errors[] = "Business name is required!";
(Doing the same line for each $_POST variable)
Basically it's an if/else statement in one line (reduces clutter). If there is data in $_POST["business_name"], then $business_name will have the value parsed through test_input - if it has no value, then the errors array gets a new value!
After checking all the values and parsing them, you can do:
if(empty($errors)) {
//If there are no errors, continue inserting
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address) VALUES ('$yard', '$full_address', '$business_name', '$business_status', '$first_name', '$last_name', $landline_number', '$mobile_number', '$business_status')";
if ($conn->query($sql) === TRUE) {
$yard_confirmation = $yard . "successfully saved.";
} else {
$yard_confirmation = "Error: " . $sql . "<br>" . $conn->error;
}
} else {
foreach($errors as $error) {
echo $error."<br />";
}
}
I would definitely recommend using PDO though, it allows you to bind values to queries.
'Dom's Business Name' is invalid, you'll need to escape it:
'Dom\'s Business Name'
Please consider using prepared statements.
You SQL-injected your own database lol. Though you do have a function for adding slashes called test_input() you forgot to use it in some places. Change these:
$business_name = $_POST["business_name"];
$landline_number = $_POST["landline_number"];
$mobile_number = $_POST["mobile_number"];
$email_address = $_POST["email_address"];
To these:
$business_name = test_input($_POST["business_name"]);
$landline_number = test_input($_POST["landline_number"]);
$mobile_number = test_input($_POST["mobile_number"]);
$email_address = test_input($_POST["email_address"]);
I'd encourage reading this.
Consider this php function http://php.net/manual/en/mysqli.real-escape-string.php and prepare your string before saving into database.
As others said, the problem is with apostrophe in the business name, but it could be with other characters that need to be escaped. And worst, your code is a candidate to be a victim of SQL injection.
For a solution, line:
$business_name = $_POST["business_name"];
should be changed by :
if ($_POST["business_name"] = "") {
$business_name_error = "Business name is required";
} else {
$business_name = test_input($_POST["business_name"]);
}
And the following three lines should be change in the same way.
In your query, your listed values, you're missing a single quote before "$landline_number".
Also, since you're not using prepared statements, I HIGHLY recommend you use mysqli_real_escape_string() for all user submitted variables to prevent injection. For example:
$variable = mysqli_real_escape_string($conn, $_POST['variable']);

Categories