A text form field needs to be required - php

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.

Related

Select All Form Fields In A Single Instance With PHP

I'm starting to learn PHP and have the code below, which includes a connection to the database from a db.php file, which then runs a query which uses HTML form data that is added to a MYSQL database.
In the code below there is an if statement that means the $firstname field must have content. If I have a larger form and want to ensure every form field is filled in, is there a PHP function where I can select all form fields with a "name" attribute (or something similar)? I appreciate I could write out the if statement x number of times for each field but I was thinking there must be an inbuilt PHP function for this? But I couldn't see anything in the PHP docs?
Any help would be wonderful.
<?php include "db.php"; ?>
<?php
if (isset($_POST['submit'])) {
$firstname = $_POST['first-name'];
$email = $_POST['email'];
if ($firstname == "" || empty($firstname)) {
echo "This field should not be empty";
} else {
$query = "INSERT INTO user(firstname, email) VALUE('{$firstname}', '{$email}')";
$add_name_query = mysqli_query($connection, $query);
if (!$add_name_query) {
die('QUERY FAILED' . mysqli_error($connection));
}
}
}
?>
You could build your own function to make it a little more "dry".
<?php
$firstname = $_POST['first-name'];
$email = $_POST['email'];
$anotherField = "Something";
$andOneMoreField = "Nothing";
function checkInputField($inputField) {
if($inputField == "" || empty($inputField)) {
echo 'This field should not be empty';
return false;
} else {
return true;
}
};
if(
checkInputField($firstname) &&
checkInputField($email) &&
checkInputField($anotherField) &&
checkInputField($andOneMoreField)
// and so on...
) {
echo "Open doors for SQL-Injection";
// db-handling
}
?>
But this is only as food for thought for further learning. This is neither nice code nor a recommendation for implementation.
Another way to do the same:
<?php
function isEmptyField($value) {
return (trim($value) == "" || empty($value)) ? true : false;
}
$fieldNames = array('first-name', 'email'); //You can add others fields name here.
$fieldsOk = true;
foreach($fieldNames as $fieldName) {
if(! array_key_exists($fieldName, $_POST) || isEmptyField($_POST[$fieldName])) {
echo "The field {$fieldName} should not be empty! \r\n";
$fieldsOk = false;
//break; //You could break the validation if a field is empty.
}
}
if($fieldsOk) {
//TODO: INSERT QUERY!
}
?>
But I think you will need others validations for each field according to their data types.

Why does this "if" statement get triggered?

I've been working for the past 5 hours on why does this if get triggered...
Let me show you the code and explain you :
<?php
require_once "ConnectDB.php";
$link2 = $link;
$key = $posthwid = "";
$err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["key"])){
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (1)";
}
else{
$key = trim($_POST["key"]);
}
$hwid = $_POST["hwid"];
if(empty($err)){
$sql = "SELECT hwid, idkey, length, created_at FROM money WHERE idkey = '" .$key. "'";
$row = mysqli_query($link, $sql);
if(mysqli_num_rows($row) < 2){
while($result = mysqli_fetch_assoc($row)) {
if($result["idkey"] == $key)
{
$err = "key";
if($result["hwid"] == "")
{
$err = "nohwid";
$sql2 = "UPDATE IceCold SET hwid = '" .$hwid. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)){
$hwid = $result["hwid"];
mysqli_close($link2);
echo "debug";
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
if ($hwid !== $result["hwid"]) {
$err = "Contact the support";
}
elseif($_SESSION["admin"] == true) {
//Do special stuff
}
else {
///do other checks
if($created_at > $date){
$err = $hwid;
} else {
$err = "The key date is too old, buy a new one.";
}
}
}
else{
$err = "The key you entered was not valid.";
}
} mysqli_close($link);
} else {
$err = "multiple entry, contact support";
}
}
} else {
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (3)";
}
echo $err;
?>
So basically, I have this Connect DB file with a mysqli_connect called $link and I'm designing a liscence API for my program. My program will send a request with the "idkey" and "hwid" and is waiting for the hwid to come back. I have an entry in my sql databse with only a key registered and I've trying to make my program wotk by generating POST request with the id and a random hwid but I've found no success. If variables are weirdly moved around, It's because of the debugging.
Right now, with my current setup, I get the Contact the support response which I don't understand why?!? The request and the key are correct if I'm able to get this awnser.
It's probably a stupid mistake but I jsut can't figure it out...
Thanks in advance for your help
Edit: the if statement I'm referring to is this:
if($hwid !== $result["hwid"])
There was a typo in the code that I fixed but it wasn't the issue,
as for the elseif, that would destroy the order of execution of the code and destroy the logic behind it(If that made sense).
Weirdly, after some tests, I found out that the second SQL request I send doesn't want to be executed ($sql2) and there is no error in httpd logs... Can you execute two requests? I tried to create $link2 but it doesn't change anything
EDIT : Found solution
if($result["hwid"] == "")
{
$sql2 = "UPDATE money SET hwid = '" .$_POST["hwid"]. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)) {
$newhwid = $_POST["hwid"];
mysqli_close($link2);
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
elseif ($_POST["hwid"] != $result["hwid"]) {
$err = "Contact the support";
}
if($_POST["hwid"] == $newhwid || $_POST["hwid"] == $result["hwid"] ) {
/// do other checks
}
The condition before that one, if($row['hwid'] = ""), is an assignment. This code is changing the value of $row['hwid'] to an empty string, causing the condition after it to be true. I assume you meant to write == to test if $row['hwid'] is empty; otherwise it doesn't make sense to write this as an if statement.
By the way, it's not clear whether this if statement shouldn't be an else if. The rest of the branches here are else if (or elseif, which is the same in PHP), so you should consider whether you have missed out an else on this one too.

Form and SQL Validation using 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;

Unable to get Table Name using variable string MYSQL Error

if ($_GET['category'] == "ebooks")
{ $tableName = $smallsubcodewithoutspace.'_ebooks';
$sectionTitle = "Ebook";
}
elseif ($_GET['category'] == "syllabus")
{ $tableName = $smallsubcodewithoutspace.'_syllabus';
$sectionTitle = "Syllabus";
}
elseif ($_GET['category'] == "pnotes")
{ $tableName = $smallsubcodewithoutspace.'_pnotes';
$sectionTitle = "Practical Note";
}
elseif ($_GET['category'] == "assignments")
{ $tableName = $smallsubcodewithoutspace.'_assignments';
$sectionTitle = "Assignment";
}
elseif ($_GET['category'] == "tnotes")
{ $tableName = $smallsubcodewithoutspace.'_tnotes';
$sectionTitle = "Theory Notes";
}
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
//very basic validation
if($contentTitle ==''){
$error[] = 'Please enter the Content Title !';
}
if($contentLink ==''){
$error[] = "Please enter the Content Link !";
}
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare("INSERT INTO `$tableName` (contentTitle,contentLink,contentAuthor) VALUES (:contentTitle, :contentLink, :contentAuthor)") ;
$stmt->execute(array(
':contentTitle' => $contentTitle,
':contentLink' => $contentLink,
':contentAuthor' => $contentAuthor
));
//redirect to index page
header('Location: add-content.php?notallowed=true');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<div align="center" class="alertpk"><div class="alert alert-warning" role="alert">'.$error.'</div></div>';
}
}
Actually, problem started when I tried inserting Table name with variable. Tables exist in database. total 5 databases are there in which I will insert data according to users selection, but when form executed, a error is thrown saying:
SQLstate[42000]: SYNTAX ERROR OR ACCESS VIOLATION 1103, INCORRECT TABLE NAME ' '
The error INCORRECT TABLE NAME '' error means you don't have a value in $tableName. Your $_GET['category'] is not picking up a recognized value or the extract($_POST) is changing $tableName to an empty value.
I got the solution, I shifted tableVariables section inside try and its now working.
var dump your variable, post to see what value comes up.

Php Single page form processing issue

(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:
First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?
Here is my code:
<?php
if ($_POST['form'] == "Submit") {
$err = array();
$filed = addslashes($_FILES['file']['tmp_name']);
$img_named = addslashes($_FILES['file']['name']);
$img_type = addslashes($_FILES['file']['type']);
#$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));
function getExtension($str)
{
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$extension = getExtension($img_named);
$extension = strtolower($extension);
$image_named_uniq = uniqid() . '.' . $extension;
$upload_path_dis = 'user/manage/discussionimg/';
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else {
$uname = $_SESSION['uname']; //session username
if (empty($sub) && empty($msg) && empty($filed))
$err[] = "All field required";
else {
if (empty($sub))
$err[] = "Subject Requried";
if (empty($msg))
$err[] = "Message Requried";
if (empty($filed))
$err[] = "SORRY, you have to be upload a image";
}
}
if (!empty($err)) {
foreach ($err as $er) {
echo "<font color=red>$er</font><br/>";
}
}
else {
$sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
if (!$sql)
echo "Can't submit your discussion" . mysql_error();
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
die('File Not Uploading');
} else {
echo "Discussion was submitted";
}
}
}
?>
Many Thanks for your help!!
Kanta.
Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"]; ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert. You have to do few controls. However these things depend on your data.
a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.

Categories