PHP Form not validating - php

Am trying to validate a form and the values of the form can only be inserted into the database if the security answer is correct.Yet the values gets inserted when a wrong answer is given.
if(empty($answer) && (!$answer == $sec_ans)) {
echo "<div class='db_rp'>Error: You did not answer your security question</div>";
} else {
$insert = "INSERT INTO laits SET
p_no = '{$new_pp}',
r_number= '{$r_number}',
memo = '{$memo}',
user= '{$userid}',
acc = '{$acc}'";
if(!mysqli_query($conn, $insert)) {
die('<div class="reply"> There was an error submtting your request ' . mysqli_error($conn)) . '</div>';
}
else {
header("location: tran_su.php");
}
}

Your code is requiring both conditions and should be only one as a minimum.
if(empty($answer) || ($answer != $sec_ans)) {
....

if (empty($answer) || ($answer != $sec_ans)) {

Related

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.

Testing condition between a php form variable and a string?

I am trying to test if $accesslevel is "admin" or "member", however I seem to have an error in my code. The input of the form is text.
Here is my control page:
public function addPerson()
{
// GET AND SET POSTED DATA
$username = $this->input->post('username');
$password = $this->input->post('password');
$accesslevel = $this->input->post('accesslevel');
$myerror = "";
// add the person to database with
if (($accesslevel != "admin") || ($accesslevel != "member"))
{
$myerror = "<br> Access level must be either member or admin.";
}
if(strlen($myerror)==0)
{
$this->db->query("INSERT INTO usersas6 "."(compid,username,password,accesslevel) VALUES "."(null,'$username', '$password', '$accesslevel')");
$this->getAllPerson();
$this->template->show('Admin', $this->TPL);
}
if(strlen($myerror) != 0){
$this->TPL["myError"] = $myerror;
$this->getAllPerson();
$this->template->show('Admin', $this->TPL);
}
}
I am also getting a warning (Undefined Variable) on my view page when I display the contents of $myError. How do I properly put $this->TPL["myError"] = $myerror; into an array so that I do not get this warning?
You can edit your code like this, make the $this->TPL["myError"] = $myerror; out side or put it in both statements
if (($accesslevel != "admin") || ($accesslevel != "member"))
{
$myerror = "<br> Access level must be either member or admin.";
}
$this->TPL["myError"] = $myerror;
if(strlen($myerror)==0)
{
$this->db->query("INSERT INTO usersas6 "."(compid,username,password,accesslevel) VALUES "."(null,'$username', '$password', '$accesslevel')");
$this->getAllPerson();
$this->template->show('Admin', $this->TPL);
}
else if(strlen($myerror) != 0){
$this->getAllPerson();
$this->template->show('Admin', $this->TPL);
}

PHP/mySQLi update values where user exists

We'll get to the point...
I have a simple form (2 of them) that relies off the previous filled out.
The intention of these forms are to sign, post to db, validate email. After the user validates their email their permission will change to be able to see the next form.
These forms work great, and everything is functional in exception to this last bit.
I am having difficulty with the form applying the values to the db table when there is existing user.
What I would like to do is only have it update the keys for that user where users session-ed API key =$API AND form_ica_initials is NULL in the roster table. If it does then will INSERT INTO
Here is what I have cleaned up. (originally wrote for the first phase of the forms to be filled out, trying to tweak to work for last half of forms)
if (empty($_POST['initials'])) { $error[] = 'You must enter your initials in every box below.'; }
else { $initials = $_POST['initials']; }
$API = $_SESSION['API'];
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API ='$API'";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (!$result_verify_form) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_form) == 0) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE `roster`
(
`fullname`, `form_ica_initials`, `form_icaauth`,`form_ica_ip`
)
VALUES (
'$fullname', '$initials', '$form_icaauth','$DOCSIGNEDBYIP'
)
";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) {
...
echo '<br><center><div class="success">...</div>';
}
else {
echo '<center><div class="error">...</div></center>';
}
}
else {
echo '<center><div class="warning" >...</div></center>';
}
}
else {
echo '<center><div class="info"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div></center>';
}
mysqli_close($dbc); //Close the DB Connection
}
If I change the if (mysqli_num_rows($result_verify_form) == 0) { to ==1 It will post the values to the table by creating a new record, and not update the existing users fields as specified. However, by doing that it will circumvent the errors that I have structured.
I know my way around PHP a bit... but having difficultly with this one
I was able to get it to work with the following.
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API='$API' AND form_ica_initials IS NULL";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (mysqli_num_rows($result_verify_form) == 1) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE roster SET fullname='$fullname', form_ica_initials='$initials', API='$API', form_icaauth='$form_icaauth', form_ica_ip='$DOCSIGNEDBYIP'";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo '<center><div class="error">Query Failed </div></center>';
}
First I had to change if (mysqli_num_rows($result_verify_form) == 1) from 0 to 1 to return Yes we've found that record.
I then had to change the INSERT INTO ... VALUES to UPDATE ... SET. I added also added AND form_ica_initials IS NULL to validate that the user hasn't completed this form yet. IF they have, then we'd prompt with a message to check their email. If they havent then we'd run the UPDATE

How to split if else error condition

I have a validation with some if/else statements.
<?php
if (isset($_POST["join"])) {
if ($userpoint < $lessonpoint) { //pt
echo "you need more points";
} //pt
else { //has enough point
if ($row['num'] > 0) { //check if user took this lesson
echo "you took this lesson before.";
} //check if user took this lesson ends
else { //then let him apply to database
//define post:
$postvalue = (int)$_POST["postvalue"];
//and check
if($postvalue == '' || $postvalue <= 0 || $postvalue > $minimumpostvalue || $postvalue == is_int($postvalue)) { //check post
echo "Error.";
} //checkpost ends.
else { //insert
$sql = "INSERT into etc... VALUES (?, ?, ?)";
if($sql){ //to another database
$artibir = "UPDATE etc.";
echo "Done.";
} // to another database
}//insert
} //let him apply
} //has enough point
} //if post isset join
?>
This works very well.
But I want to echo out another error message for this condition: $postvalue > $minimumpostvalue
While trying it I get lost inside the if/else statements.
Wherever I put new statement I'm having an error.
All variables are defined.
Where and how can I place $postvalue > $minimumpostvalue to echo a different error message?
<?php
if (isset($_POST["join"])) {
if ($userpoint < $lessonpoint) { //pt
echo "you need more points";
} //pt
else { //has enough point
if ($row['num'] > 0) { //check if user took this lesson
echo "you took this lesson before.";
} //check if user took this lesson ends
else { //then let him apply to database
//define post:
$postvalue = (int) $_POST["postvalue"];
//and check
if ($postvalue == '' || $postvalue <= 0 || $postvalue > $minimumpostvalue || $postvalue == is_int($postvalue)) { //check post
if ($postvalue > $minimumpostvalue) {
echo "Another Error.";
}
else {
echo "Error.";
}
} //checkpost ends.
else { //insert
$sql = "INSERT into etc... VALUES (?, ?, ?)";
if ($sql) { //to another database
$artibir = "UPDATE etc.";
echo "Done.";
} // to another database
} //insert
} //let him apply
} //has enough point
} //if post isset join
?>
This is another variation without exceptions.
As soon as $valid becomes false, it will skip the next validation.
<?php
$valid = true;
$error = '';
if ($valid && !isset($_POST["join"])) {
$error = 'Not a join post request';
$valid = false;
}
if ($valid && ($userpoint < $lessonpoint)) {
$error = 'You need more points';
$valid = false;
}
...
if($valid) {
// Database insert; redirect
} else {
// User error feedback
}
//and check
if ($postvalue > $minimumpostvalue) { //check exception
echo "Error 1.";
} elseif ($postvalue == '' || $postvalue <= 0 || $postvalue == is_int($postvalue)) { //check the rest
echo "Error 2.";
} //checkpost ends.
This is untested code, and more an example of how to avoid nested if statements.
The point is to find to state the conditions you have an error state early and exit as soon as you can, at best by throwing an exception and avoiding else statements.
For simplicity I used only \RunTimeException(), yet I would most likely define my own exception depending on the case. The exception then can be caught and depending on their type show a different error page.
/**
* #param int $postvalue
* #param int $minimumpostvalue
*/
function saveToDatabase($postvalue)
{
if ($postvalue == '' || $postvalue <= 0 || $postvalue == is_int($postvalue)) {
throw new \RuntimeException('Error 2');
}
$sql = "INSERT into etc... VALUES (?, ?, ?)";
if ($sql) {
$artibir = "UPDATE etc.";
}
}
if (!isset($_POST["join"])) {
throw new \RuntimeException('Not a join post request');
}
if ($userpoint < $lessonpoint) {
throw new \RuntimeException('You need more points');
}
$userHasTakenCourse = $row['num'] > 0;
if ($userHasTakenCourse) {
throw new \RuntimeException('User has already taken the course.');
}
$postvalue = (int) $_POST["postvalue"];
if ($postvalue > $minimumpostvalue) {
throw new \RuntimeException('Error 1');
}
saveToDatabase($postvalue);

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.

Categories