Passing variables into a mysqli prepared statement - php

I have been self teaching myself php in my spare time using you tube and w3 schools. So far I have been mostly successful but have hit a brick wall with a particular issue.
I am trying to use a prepared statement to load data into a database (Xampp myphp admin). I have attached my code below and have done a range of testing based on internet searches. When I run the code I get no error message but nothing inserts into my database. I am fairly certain it is do with passing the variables into the bind_param() placeholders.
Please ignore the fact the headings don't match the data types as I want to get data inserting into the database first.
Thanks
<?php
include 'dbh.php';
class AddData extends Dbh {
public function submitTableData(){
$dateErr = $starttimeErr = $finishtimeErr = $durationErr = $taskErr = $entityErr = $completeErr = $commentsErr = "";
$date = $starttime = $finishtime = $duration = $task = $entity = $complete = $comments = "";
$query = "INSERT INTO testtable(Date, Starttime, Finishtime, Duration, Task, Entity, Complete, Comments) VALUES (?,?,?,?,?,?,?,?)";
$stmt= $this->connect()->prepare($query);
$stmt->bind_param("ssssssss", $date, $starttime, $finishtime, $duration, $task, $entity, $complete, $comments);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
for ($x = 0; $x < 1; $x++) {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"][$x])) {
$dateErr = "date is required";
} else {
$date = test_input($_POST["date"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$date)) {
$dateErr = "Only letters and white space allowed";
}
}
if (empty($_POST["starttime"][$x])) {
$starttimeErr = "starttime is required";
} else {
$starttime = test_input($_POST["starttime"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$starttime )) {
$starttimeErr = "Only letters and white space allowed";
}
}
if (empty($_POST["finishtime"][$x])) {
$finsihtimeErr = "finishtime is required";
} else {
$finishtime = test_input($_POST["finishtime"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$finishtime)) {
$finishtimeErr = "Only letters and white space allowed";
}
}
if (empty($_POST["duration"][$x])) {
$durationErr = "Name is required";
} else {
$duration = test_input($_POST["duration"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$duration)) {
$durationErr = "Only letters and white space allowed";
}
}
if (empty($_POST["task"][$x])) {
$taskErr = "task is required";
} else {
$task = test_input($_POST["task"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$task)) {
$taskErr = "Only letters and white space allowed";
}
}
if (empty($_POST["entity"][$x])) {
$entityErr = "Name is required";
} else {
$entity = test_input($_POST["entity"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$entity)) {
$entityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["complete"][$x])) {
$completeErr = "complete is required";
} else {
$complete = test_input($_POST["complete"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$complete)) {
$completeErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comments"][$x])) {
$commentsErr = "comments is required";
} else {
$comments = test_input($_POST["comments"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comments)) {
$commentsErr = "Only letters and white space allowed";
}
}
}
$stmt->execute();
}
$stmt->close();
$this->connect()->close();
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$t1 = new AddData;
$t1->submitTableData();
}
?>

Related

PHP OOP - How to validate input fields correctly

This is my Form - This an Include File.
form_file.php
<section class="container-sm">
<form method="post" class="par-form">
<h3 class="par-h2">John Doe Form</h3>
<p><label class="single-label" for='user_firstname'>Name: <a id='user_firstname_label'></a></label>
<input class="par-input form_login" maxlength="15" name="user_firstname" required value="<?=$obVaga->user_firstname?>" ></input><span class="error">*<?php echo $nameErr;?></span></p>
<p><label class="single-label" for='user_secondname'>Surname: <a id='user_secondname_label'></a></label>
<input class="par-input form_login" maxlength="40" name="user_secondname" required value="<?=$obVaga->user_secondname?>" ></input></p>
<p><label class="single-label" for='user_email'>E-mail: <a id='user_email_label'></a></label>
<input class="par-input form_login" maxlength="40" name="user_email" required value="<?=$obVaga->user_email?>" ></input></p>
<button type="button" onclick="sendData()" class="par-button" id='user_button_sendData'>SEND</button>
</form>
</section>
This is the template page that receives the Form file
single-add.php
<?php
/**
* Acess the composer library
*/
require __DIR__.'/vendor/autoload.php';
/**
* Use a Classe VAGA
*/
use \App\Entity\Vaga;
$obVaga = new Vaga;
if (isset($_POST['user_firstname'],$_POST['user_secondname'],$_POST['user_email'])) {
$obVaga->user_firstname = $_POST['user_firstname'];
$obVaga->user_secondname = $_POST['user_secondname'];
$obVaga->user_email = $_POST['user_email'];
$obVaga->user_cadastrar();
}
?>
<!-- Receive the contents of the form include form_file.php -->
<?php include __DIR__.'/appincludes/form_file.php' ?>
This is the Class page that receives the data
Vaga.php
<?php
namespace App\Entity;
/**
* Use a Classe Database
*/
use \App\Db\Database;
use PDO;
class Vaga{
// #var Integer
public $user_id;
// #var String
public $user_firstname;
// #var String
public $user_secondname;
// #var String
public $user_email;
// #var String
public $nameErr;
// #var Boolean
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_firstname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_secondname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_secondname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
public function user_cadastrar(){
// DEFINIR A DATA
// INSERT STRINGs IN THE TABLE
$obDatabase = new Database('tb_partner');
$this->id = $obDatabase->insert([
'user_firstname' => $this->user_firstname,
'user_secondname'=> $this->user_secondname,
'user_email' => $this->user_email
]);
}
}
I´m trying to use this script to validate the fields, but I am stuck. I`m trying to execute this script through the class file Vaga.php
public function par_add_validate(){
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_firstname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_secondname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_secondname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
};
}
I putted the Var $nameErr in the form_file.php where it should display an echo string IF the field is empty or with not acceptable letters.
This is the result in the debug.log file:
[18-Aug-2021 16:44:07 UTC] PHP Notice: Undefined variable: nameErr in C:\xampppserver2\htdocs\project\appincludes\form_file.php on line 15
Line 15:
<input name="user_firstname" required value="<?=$obVaga->user_firstname?>" ></input><span>*<?php echo $nameErr;?></span></p>
What am I doing wrong or what is missing?
I believe you have some lines missing here:
// #var Boolean
if ($_SERVER["REQUEST_METHOD"] == "POST") {
Otherwise you've put some logic code right inside your class (without method) which should result in a Parse error. Also why is there #var Boolean with no boolean property following?
Given that you wrap all that code in a method, you still have several issues. First, you can't access $nameErr directly. Instead, you want $this->nameErr.
And in form_file.php you also have no variable called $nameErr. You have nameErr as a property of $obVaga object though. You can access it using $obVaga->nameErr.

Not working. Validation and sanitizing via PHP suddenly not working

I have a weird problem. First of all, before I did form validation via PHP, I could insert and display data ( I have at least 30 fields). Then after I did validation and sanitizing, suddenly I cannot insert and display data. After I remove some fields and columns in the database, which left me a few, now I can insert data and display data, but if I add more than lets say 5 or 6 fields, I cannot insert data. Please tell me what's wrong?
<?php
echo var_dump($_POST);
echo var_dump($_FILES);
print_r($_SESSION);
error_reporting(E_ALL);
ini_set("display_errors",1);
//define variables and define to null.
$adtitleError = $dcrptnError = $rmError = $advertnameError = $apE = "";
$adtitle = $dcrptn = $rm = $advertname = $ap = "";
//Retrieve the field values from registration form.
$adtitle = !empty($_POST ['adtitle']) ? trim($_POST['adtitle']) : null;
$dcrptn = !empty($_POST ['dcrptn']) ? trim($_POST['dcrptn']) : null;
$rm = !empty($_POST ['rm']) ? trim($_POST['rm']) : null;
$advertname = !empty($_POST ['advertname']) ? trim($_POST['advertname']) : null;
$ap = !empty($_POST ['adphone']) ? trim($_POST['adphone']) : null;
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true;
if(isset($_POST["submit"])){
//insert record
if($conn->connect_error)
{die("Connection failed:".$conn->connect_error);}
$id=isset($_POST['id'])?$_POST['id']:"";
//insert data
$statement = $conn->prepare("INSERT INTO useradvert(id,image1,adtitle,dcrptn,rm,advertname,adphone)VALUES (?,?,?,?,?,?,?)");
//bind param
$statement->bind_param("issssss",$id,$target_file,$adtitle,$dcrptn,$rm,$advertname,$ap);
$target_file=isset($_FILES['image'])?$_FILES['image']:"";
$adtitle=isset($_POST['adtitle'])?$_POST['adtitle']:"";
$dcrptn=isset($_POST['dcrptn'])?$_POST['dcrptn']:"";
$rm=isset($_POST['rm'])?$_POST['rm']:"";
$advertname=isset($_POST['advertname'])?$_POST['advertname']:"";
$ap=isset($_POST['adphone'])?$_POST['adphone']:"";
//bind the variables to be called at other places
if (empty($adtitle)){
$adtitleError = "Ad title is required. Select category to activate form.";
$formValid = false;
}else{
$adtitle = test_input($_POST["adtitle"]);
// check name only contains letters and whitespace
if (!preg_match('/^[a-zA-Z\s]{3,50}+$/', $adtitle)) {
$adtitleError = "Letters only & spaces,(min 3),e.g: a, A)";
$formValid = false;
}
}
if (empty($dcrptn)){
$dcrptnError = "Decsription is required. Select category to activate form.";
$formValid = false;
}
if (empty($rm)){
$rmError = "A value is required, e.g: 123000 or 12,300.00. Select category to activate form.";
$formValid = false;
}
else{
$rm = test_input($_POST["rm"]);
// check name only contains letters and whitespace
if (!preg_match('/^[0-9]+(?:\.[0-9]{1,13})?$/',$rm)) {
$rmError = "Invalid value.E.g: 123000.45. Select category to activate form.";
$formValid = false;
}
}
if (empty($advertname)){
$advertnameError = "Name is required. Select category to activate form.";
$formValid = false;
}
else{
$advertname = test_input($_POST["advertname"]);
// check name only contains letters and whitespace
if (!preg_match('/^[a-zA-Z\s]{3,50}+$/',$advertname)) {
$advertnameError = "Letters only & spaces,(min 3),(e.g: a, A). Select category to activate form.";
$formValid = false;
}
}
if (empty($ap)){
$apE = "Tel number is required. Select category to activate form.";
$formValid = false;
}
else{
$ap= test_input($_POST["adphone"]);
// check name only contains letters and whitespace
if (!preg_match('/^\d{9,11}+$/',$ap)) {
$apE = "Invalid tel no format.( E.g:0123456789). Select category to activate form.";
$formValid = false;
}
}
//image
$target_dir="uploads/";
$target_file=$target_dir.basename($_FILES["image1"]["name"]);
$uploadOk=1;
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
//script for targetfile -image
// Check if image or not
$check=getimagesize($_FILES["image1"]["tmp_name"]);
if($check!==false){
echo "File is an image - ".$check["mime"].".";
$uploadOk=1;
}else{
echo "File is not an image.";
$uploadOk=0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk=0;
}
// Check file size
if ($_FILES["image1"]["size"]>500000) {
echo "Sorry, your file is too large.";
$uploadOk=0;
}
// Allow certain file formats
if($imageFileType!="jpg"&&$imageFileType!="png"&&$imageFileType!="jpeg"
&&$imageFileType!="gif")
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk=0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}else{
if (move_uploaded_file($_FILES["image1"]["tmp_name"],$target_file)) {
echo "The file ".basename($_FILES["image1"]["name"])."has been uploaded.";
}else{
echo "Sorry, there was an error uploading your file.";
}
}
if ($formValid){
$statement->execute();
header('Location: userpppp.php');
exit;
}
}
?>

trying to compare two email fields - page blanks out

Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}

Logic for form validation before insert into database

I would like to write a logic for data validation before insert into database. If the data not valid, then it will prompt user errors, but then I facing problem which not the logic that I wish:
(1) Message "Data successfully inserted!" shown even the error checking message was prompt.
(2) Message "Data successfully inserted!" shown even no data was entered in the form then click submit.
How should I change the logic to the one that I wish to have?
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$comp_nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["comp_licensee_name"])) {
$compLicenseeNameError = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
//php code ends here
?>
<html>
<head>
<link rel="stylesheet" href="style/style.css" />
</head>
<body>
<div class="maindiv">
<div class="form_div">
<form method="post" action="compReg.php">
<span class="error">* required field.</span>
<br>
<hr/>
<br>
Company Name:<br><input class="input" type="text" name="comp_name" value="">
<span class="error">* <?php echo $comp_nameError;?></span>
<br>
Company Licensee:<br><input class="input" type="text" name="comp_licensee_name" value="">
<span class="error">* <?php echo $compLicenseeNameError;?></span>
<br>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
I'd accumulate the errors into an array, and proceed to the insert part only if it's empty:
$errors = array();
if (empty($_POST["comp_name"])) {
$errors[] = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$errors[] = "Only letters and white space allowed in the computer name";
}
}
if (empty($_POST["comp_licensee_name"])) {
$errors[] = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
if (!empty($errors)) {
echo "The following errors occurred:<br/>" . implode('<br/>', $errors);
exit();
}
// If we didn't exit, continue to the insertion code
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {
$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
// check boolean variable value
$is_valid = 1;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$validation_error = "Only letters and white space allowed";
$is_valid = 0;
}
}
if (empty($_POST["comp_licensee_name"])) {
$validation_error = "Company Licensee Name is required";
$is_valid =0;
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
if($is_valid == 1 ){
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
} else {
echo $validation_error;
die;
}
}
//php code ends here
?>

validate my form and header to another success page

I am trying to validate my form fields and redirect the user to success page
so this is the PHP code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$experiences = $courses = $careerObjective = $availability = $typeOfJob = $rank = $jTitle = $otherJobTitle
= $salaryRange = $currency = $workIn = "";
$experiencesErr = $coursesErr = $careerObjectiveErr = $availabilityErr = $typeOfJobErr = $rankErr = $jTitleErr
= $otherJobTitleErr = $salaryRangeErr = $currencyErr = $workInErr = "";
$id = "";
$uid = "";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$error = array(
"coursesErr"=>"",
"careerObjectiveErr"=>"",
"otherJobTitleErr"=>"",
"experiencesErr"=>"",
"availabilityErr"=>"",
"typeOfJobErr"=>"",
"rankErr"=>"",
"jTitleErr"=>"",
"salaryRangeErr"=>"",
"currencyErr"=>"",
);
if (empty($_POST['experiences'])) {
$error['experiencesErr'] = "Experiences Required";
} else {
$experiences = check_input($_POST['experiences']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $experiences)) {
$error['experiencesErr'] = "Only letters, numbers and '_' allowed";
}
}
$courses = check_input($_POST['courses']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $courses)) {
$error['coursesErr'] = "Only letters, numbers and '_' allowed";
}
$careerObjective = check_input($_POST['careerObjective']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $careerObjective)) {
$error['careerObjectiveErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['availability'])) {
$error['availabilityErr'] = "Availability Required";
} else {
$availability = check_input($_POST['availability']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['rank'])) {
$error['rankErr'] = "Self-assessment Required";
} else {
$rank = check_input($_POST['rank']);
}
if (empty($_POST['jTitle'])) {
$error['jTitleErr'] = "Job Field Required";
} else {
$jTitle = check_input($_POST['jTitle']);
}
$otherJobTitle = check_input($_POST['otherJobTitle']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $otherJobTitle)) {
$error['otherJobTitleErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['salaryRange'])) {
$error['salaryRangeErr'] = "Salary Range Required";
} else {
$salaryRange = check_input($_POST['salaryRange']);
}
if (empty($_POST['currency'])) {
$error['currencyErr'] = "Currency Required";
} else {
$currency = check_input($_POST['currency']);
}
$workIn = check_input($_POST['workIn']);
if(!$error){
$putData = $db->prepare("INSERT INTO hired_ts_info (id, uid, experiences, courses, career_objective,
availability, type_of_job, rank, job_title, other_job_title, salary_range, currency, workIn)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$putData->bind_param('iisssssssssss', $id, $uid, $experiences, $courses, $careerObjective, $availability,
$typeOfJob, $rank, $jTitle, $otherJobTitle, $salaryRange, $currency, $workIn);
if($putData->execute()){
header("Location:?pid=4&pp=2&pps=technicalSummary&m=g");
}else{
echo "Error on executing";
}
}
}
?>
and this is the first lines of the HTML code
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" id="personRegestrationPage4">
<div class="f_left width100percent">
<div class="TwoLine">
<label for="experiences" class="requiredFields">experiences and qualifications</label>
<textarea name="experiences" id="experiences"></textarea>
<span class="notAllowed"><?php if (isset($error)) {
echo $error['experiencesErr'];
}?></span>
</div>
<div class="TwoLine">
<label for="courses">Previous Courses</label>
<textarea name="courses" id="courses"></textarea>
<span class="notAllowed"><?php if (isset($error)) {
echo $error['coursesErr'];
} ?></span>
</div>
</div>
and this is the submit button code
<input type="submit" name="subTs" id="subTs" value="Save Changes" class="submitBtn4">
Problem
now when I submit the form it come back without inserting anything to the db and no error message received
Update
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$experiences = $courses = $careerObjective = $availability = $typeOfJob = $rank = $jTitle = $otherJobTitle
= $salaryRange = $currency = $workIn = "";
$experiencesErr = $coursesErr = $careerObjectiveErr = $availabilityErr = $typeOfJobErr = $rankErr = $jTitleErr
= $otherJobTitleErr = $salaryRangeErr = $currencyErr = $workInErr = "";
$id = "";
$uid = "";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$error = array();
if (empty($_POST['experiences'])) {
$error['experiencesErr'] = "Experiences Required";
} else {
$experiences = check_input($_POST['experiences']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $experiences)) {
$error['experiencesErr'] = "Only letters, numbers and '_' allowed";
}
}
$courses = check_input($_POST['courses']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $courses)) {
$error['coursesErr'] = "Only letters, numbers and '_' allowed";
}
$careerObjective = check_input($_POST['careerObjective']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $careerObjective)) {
$error['careerObjectiveErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['availability'])) {
$error['availabilityErr'] = "Availability Required";
} else {
$availability = check_input($_POST['availability']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['rank'])) {
$error['rankErr'] = "Self-assessment Required";
} else {
$rank = check_input($_POST['rank']);
}
if (empty($_POST['jTitle'])) {
$error['jTitleErr'] = "Job Field Required";
} else {
$jTitle = check_input($_POST['jTitle']);
}
$otherJobTitle = check_input($_POST['otherJobTitle']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $otherJobTitle)) {
$error['otherJobTitleErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['salaryRange'])) {
$error['salaryRangeErr'] = "Salary Range Required";
} else {
$salaryRange = check_input($_POST['salaryRange']);
}
if (empty($_POST['currency'])) {
$error['currencyErr'] = "Currency Required";
} else {
$currency = check_input($_POST['currency']);
}
$workIn = check_input($_POST['workIn']);
if (!$error) {
$putData = $db->prepare("INSERT INTO hired_ts_info (id, uid, experiences, courses, career_objective,
availability, type_of_job, rank, job_title, other_job_title, salary_range, currency, workIn)
VALUE(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$putData->bind_param('iisssssssssss', $id, $uid, $experiences, $courses, $careerObjective, $availability,
$typeOfJob, $rank, $jTitle, $otherJobTitle, $salaryRange, $currency, $workIn);
if ($putData->execute()) {
header("Location:?pid=4&pp=2&pps=technicalSummary&m=g");
} else {
echo "Error on executing";
}
} else {
$error = array(
"coursesErr" => "",
"careerObjectiveErr" => "",
"otherJobTitleErr" => "",
"experiencesErr" => "",
"availabilityErr" => "",
"typeOfJobErr" => "",
"rankErr" => "",
"jTitleErr" => "",
"salaryRangeErr" => "",
"currencyErr" => "",
);
}
}
?>
still that didn't solve the issue
1- now the code submit correctly and gos to my DB.
2- if the fields is empty or not allowed input the message don't appear any more under the fields
any Ideas pleasee
The reason behind your script is not showing any error is this
that you set the value again for your error in the else statement which is empty; in these line
else {
$error = array(
"coursesErr" => "",
"careerObjectiveErr" => "",
"otherJobTitleErr" => "",
"experiencesErr" => "",
"availabilityErr" => "",
"typeOfJobErr" => "",
"rankErr" => "",
"jTitleErr" => "",
"salaryRangeErr" => "",
"currencyErr" => "",
);
}
in these line you set the value for your $error Arrray, and set them to empty.
The things is this even you set the array value before, but when the php reaches these line, it changes those value to empty value which you define,
For example if you have a code like this
$x=4;
$x=5;
even though you got same variable, but if you echo $x; its gonna give you always 5 cause this is the last value for $x;
to understand it more clearly what you should do give some value in any $error array in else statement it will show that $error
like this
$error = array(
"coursesErr" => "my name is spider man",
"careerObjectiveErr" => "",
"otherJobTitleErr" => "",
"experiencesErr" => "",
"availabilityErr" => "",
"typeOfJobErr" => "",
"rankErr" => "",
"jTitleErr" => "",
"salaryRangeErr" => "",
"currencyErr" => "",
);
}
and than run the code, it will show you that particular error not any other, because you set it value,
so what should you do now, easy option is this remove the else statement completely,

Categories