validate my form and header to another success page - php

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,

Related

Null values inserted in database table using php pdo

I made a PHP interface for teacher table. All columns in table is set to NOT NULL. If I submit the form with empty inputs. Empty values will be submitted to my database table teacher. I can't understand if columns of the table is set to not null why database table accepts null values from my user interface.
if(filter_has_var(INPUT_POST, "add_teacher")){
function test_input($data){
$data = stripslashes($data);
$data = trim($data);
$data = htmlspecialchars($data);
return $data;
}
if(empty($_POST["firstname"])){
$firstname_err = "* Firstname is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["firstname"])){
$firstname_err = "Invalid Firstname";
} else if (!test_input($_POST["firstname"])){
$firstname_err = "Invalid firstName, please enter a valid first name!";
} else {
$firstname = $_POST["firstname"];
}
}
if(empty($_POST["lastname"])){
$lastname_err = "* Last name is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["lastname"])){
$lastname_err = "Invalid last name";
} else if (!test_input($_POST["lastname"])){
$lastname_err = "Invalid last name, please enter a valid last name!";
} else {
$lastname = $_POST["lastname"];
}
}
if(empty($_POST["DOB"])){
$DOB_err = "* Date of birth is a required field!";
} else {
$DOB = $_POST["DOB"];
}
if(empty($_POST["gender"])){
$gender_err = "* Gender is a required field!";
} else {
$gender = $_POST["gender"];
}
if(empty($_POST["tazkira_number"])){
$tazkira_number_err = "* This is a required field";
} else {
if(!filter_var($_POST["tazkira_number"], FILTER_VALIDATE_INT)){
$tazkira_number_err = "* Only numbers are allowed";
} else if(!test_input($_POST["tazkira_number"])){
$tazkira_number_err = "* Invalid data entered";
}
else {
$tazkira_number = $_POST["tazkira_number"];
}
}
if(empty($_POST["phone_number"])){
$phone_number_err = "* This is a required field";
} else {
$phone_number = $_POST["phone_number"];
}
if(empty($_POST["academic_field"])){
$academic_field_err = "* Academic field is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["academic_field"])){
$academic_field_err = "Invalid academic field.";
} else if (!test_input($_POST["academic_field"])){
$academic_field_err = "Invalid academic field, please enter a valid academic field!";
} else {
$academic_field = $_POST["academic_field_err"];
}
}
if(empty($_POST["email"])){
$email_err = "* Email field is required!";
} else {
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
$email_err = "Invalid email entered";
} else if (!test_input($_POST["email"])){
$academic_femail_err = "Invalid data, please enter a valid email address!";
} else {
$email = $_POST["email"];
}
}
if(empty($_POST["position"])){
$position_err = "* Position field is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["position"])){
$position_err = "* Invalid data";
} else if (!test_input($_POST["position"])){
$position_err = "* Invalid data, please enter a valid position!";
} else {
$position = $_POST["position"];
}
}
if(empty($_POST["hire_date"])){
$hire_date_err = "* Hire date is a required field!";
} else {
$hire_date = $_POST["hire_date"];
}
$resign_date = $_POST["resign_date"];
$sql = "INSERT INTO teacher (firstname, lastname, DOB, gender, tazkira_number, phone_number, academic_field, email, position, hire_date, resign_date) VALUES (:firstname, :lastname, :DOB, :gender, :tazkira_number, :phone_number, :academic_field, :email, :position, :hire_date, :resign_date)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(["firstname"=> $firstname, "lastname" => $lastname, "DOB" => $DOB, "gender" => $gender, "tazkira_number" => $tazkira_number, "phone_number" => $phone_number, "academic_field" => $academic_field, "email" => $email, "position" => $position, "hire_date" => $hire_date, "resign_date" => $resign_date]);
$add_teacher_success_msg = "New teacher added successfully!";
}
As you can see above this code inserts into teacher some values. If I don't write anything in input of the form and click submit. Null or empty values will be submitted to table. Please help me solve this problem. Thank you
Your "empty values" are actually not "null" values but "empty strings" (strings with zero characters).
To make PDO recognize them as NULL values, you have to convert empty strings into null before you inserting them into database.
For example, you could create function:
// e2n means "empty to null", and made shorter for more convinient usage:
function e2n($src)
{
if (is_string($src) && trim($src) == "")
{
return null;
}
else
{
return $src;
}
}
And use it like:
$sql = "INSERT INTO teacher (firstname, lastname, DOB, gender, tazkira_number, phone_number, academic_field, email, position, hire_date, resign_date) VALUES (:firstname, :lastname, :DOB, :gender, :tazkira_number, :phone_number, :academic_field, :email, :position, :hire_date, :resign_date)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(["firstname"=> e2n($firstname), "lastname" => e2n($lastname), "DOB" => e2n($DOB), "gender" => e2n($gender), "tazkira_number" => e2n($tazkira_number), "phone_number" => e2n($phone_number), "academic_field" => e2n($academic_field), "email" => e2n($email), "position" => e2n($position), "hire_date" => e2n($hire_date), "resign_date" => e2n($resign_date)]);
Also, I recommend you to refactor your algorythm, so you have some array of fields, and names of validators, that are used for them, and walk through fields, running corresponding validators, and also make e2n conversion in place.
About error "SQLSTATE[23000]: Integrity constraint violation: 1048":
To skip insertion of data, you should add testing for your *_err variables:
$isOk = true;
//All your Error fields
$err_fields = ['firstname_err', 'lastname_err', 'DOB_err', 'gender_err', 'tazkira_number_err', 'phone_number_err', 'position_err', 'academic_field_err', 'email_err', 'hire_date_err'];
foreach ($err_fields as $field)
{
if (isset($$field) && $$field)
{
echo "You have error!<br>";
$isOk = false;
}
}
if ($isOk)
{
// Running SQL if there were no errors:
$sql = "INSERT INTO teacher (firstname, lastname, DOB, gender, tazkira_number, phone_number, academic_field, email, position, hire_date, resign_date) VALUES (:firstname, :lastname, :DOB, :gender, :tazkira_number, :phone_number, :academic_field, :email, :position, :hire_date, :resign_date)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(["firstname"=> e2n($firstname), "lastname" => e2n($lastname), "DOB" => e2n($DOB), "gender" => e2n($gender), "tazkira_number" => e2n($tazkira_number), "phone_number" => e2n($phone_number), "academic_field" => e2n($academic_field), "email" => e2n($email), "position" => e2n($position), "hire_date" => e2n($hire_date), "resign_date" => e2n($resign_date)]);
}
You're checking for invalid values, but not doing anything if you find them. I.e., you're always running the INSERT, no matter what errors you find. I'd recommend not using a separate variable for each error, but instead append errors to an array:
$errors = [];
if (empty($_POST["email"])) {
$errors[] = 'Email is required.';
}
if (empty($_POST["academic_field"])) {
$errors[] = "Academic field is required.";
}
// and so on...
Then, you can just check to see if $errors is empty to know if you have any errors:
if (empty($errors)) {
// No errors, try the insert.
$sql = "INSERT INTO teacher ...";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(...);
} else {
// Display the errors.
echo "You have errors:";
foreach ($errors as $error) {
echo $error;
}
}

my previously store data are automatically deleted while updating a data

I am currently working on a job portal project, where I can store user information,
in my project after registration, user can go there dashboard, and update there remaining form like, education detail and company detail. but after that when user like to update one of the any field in form, it can update that field but it can delete my remaining field, in education detail field or company detail field. What kind of this problem is occurred ?
updateprofile.php
<?php
session_start();
if(empty($_SESSION['id_user']))
{
header("Location: ../index.php");
exit();
}
require_once("../db.php");
if(isset($_POST))
{
//Escape Special Characters
$firstname = $conn->real_escape_string( $_POST['fname']);
$lastname = $conn->real_escape_string($_POST['lname']);
$gender = $conn->real_escape_string($_POST['gender']);
$contactno = $conn->real_escape_string($_POST['contactno']);
$address = $conn->real_escape_string($_POST['address']);
$city = $conn->real_escape_string($_POST['city']);
$state = $conn->real_escape_string($_POST['state']);
$aboutme = $conn->real_escape_string($_POST['aboutme']);
$qualification = $conn->real_escape_string($_POST['qualification']);
$stream = $conn->real_escape_string($_POST['stream']);
$coursetype = $conn->real_escape_string($_POST['coursetype']);
$university = $conn->real_escape_string($_POST['university']);
$passingyear = $conn->real_escape_string($_POST['passingyear']);
$skill = $conn->real_escape_string($_POST['skill']);
$industry = $conn->real_escape_string($_POST['industry']);
$functional_area = $conn->real_escape_string($_POST['functional_area']);
$role = $conn->real_escape_string($_POST['role']);
$is_current_job = $conn->real_escape_string($_POST['is_current_job']);
$startdate = $conn->real_escape_string($_POST['startdate']);
$enddate = $conn->real_escape_string($_POST['enddate']);
$current_compname = $conn->real_escape_string($_POST['current_compname']);
$current_salary = $conn->real_escape_string($_POST['current_salary']);
$designation = $conn->real_escape_string($_POST['designation']);
$notice_period = $conn->real_escape_string($_POST['notice_period']);
$job_desc = $conn->real_escape_string($_POST['job_desc']);
$experience = $conn->real_escape_string($_POST['experience']);
$current_location = $conn->real_escape_string($_POST['current_location']);
$prefer_location = $conn->real_escape_string($_POST['prefer_location']);
$uploadOk = true;
if(is_uploaded_file($_FILES['resume']['tmp_name']))
{
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['resume']['tmp_name']))
{
if($resumeFileType == "pdf")
{
if($_FILES['resume']['size'] < 500000)
{
// File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
}
else
{
$_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
header("Location: edit_profile.php");
exit();
}
}
else
{
$_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
header("Location: edit_profile.php");
exit();
}
}
}
else
{
$uploadOk = false;
}
//Update User Details Query
$sql = "UPDATE user SET firstname='$firstname', lastname='$lastname',gender='$gender',contactno='$contactno', address='$address', city='$city', state='$state',aboutme='$aboutme',qualification='$qualification', stream='$stream',coursetype='$coursetype',university='$university',passingyear='$passingyear',skill='$skill',
industry='$industry',functional_area='$function_area',role='$role',is_current_job='$is_current_job',startdate='$startdate',enddate='$enddate',current_compname='$current_compname',current_salary='$current_salary',designation='$designation',notice_period='$notice_period',job_desc='$job_desc',experience='$experience',current_location='$current_location',prefer_location='$prefer_location'";
if($uploadOk == true)
{
$sql .= ",resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE)
{
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
}
else
{
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection.
$conn->close();
}
else
{
//redirect them back to dashboard page if they didn't click update button
header("Location: edit_profile.php");
exit();
}
image of user table
Using prepared statements and dynamic field mapping to update only those fields which has value in it, here is what your code should look like
<?php
session_start();
if (empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
require_once("../db.php");
if (isset($_POST)) {
$uploadOk = true;
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir . $file;
if (file_exists($_FILES['resume']['tmp_name'])) {
if ($resumeFileType == "pdf") {
if ($_FILES['resume']['size'] < 500000) {
// File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
header("Location: edit_profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
header("Location: edit_profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$postf2sqlf = array(
'firstname' => 'firstname',
'lastname' => 'lastname',
'gender' => 'gender',
'contactno' => 'contactno',
'address' => 'address',
'city' => 'city',
'state' => 'state',
'aboutme' => 'aboutme',
'qualification' => 'qualification',
'stream' => 'stream',
'coursetype' => 'coursetype',
'university' => 'university',
'passingyear' => 'passingyear',
'skill' => 'skill',
'industry' => 'industry',
'functional_area' => 'function_area',
'role' => 'role',
'is_current_job' => 'is_current_job',
'startdate' => 'startdate',
'enddate' => 'enddate',
'current_compname' => 'current_compname',
'current_salary' => 'current_salary',
'designation' => 'designation',
'notice_period' => 'notice_period',
'job_desc' => 'job_desc',
'experience' => 'experience',
'current_location' => 'current_location',
'prefer_location' => 'prefer_location'
);
$sql = 'UPDATE `user` SET ';
$skipComma = true;
$params = array('');
foreach ($postf2sqlf as $p => $s) {
if (isset($_POST[$p]) && !empty($_POST[$p])) {
$sql .= ($skipComma ? '' : ',') . '`' . $s . '` = ?';
$params[] = &$_POST[$p];
$params[0] .= 's';
$skipComma = false;
}
}
if ($uploadOk == true) {
$sql .= ",resume=?";
$params = &$file;
$params[0] .= 's';
}
$sql .= " WHERE id_user=?";
$params[0] .= 's';
$params[] = &$_SESSION['id_user'];
$stmt = $db->prepare($sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
$res = $stmt->execute();
if ($stmt->errno == 0) {
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
} else {
echo "Error " . $sql . "<br>" . $conn->error;
}
//Close database connection.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit_profile.php");
exit();
}
Explanation
Created $postf2sqlf array, holding the Form fields as index, and sql field names as value.
Iterating over $postf2sqlf and checking if the index is set and not empty in $_POST, started collecting the parameters passing references in $params to use in a prepared statement to avoid SQL Injection. $params[0] holds the type (s => string) of named parameters, as mysqli_statement::bind_param requires this, and as parameters added, another s is concatenated. (For a strict sql, instead of s, other types could be used upon checking their types but for simplicity's sake I used s)
The reason to collect variables by passing references is because `mysqli_statement::bind_param requires the variables pass by references.
call_user_func_array was used to call mysqli_statement::bind_param with the $params with each index being a different argument.
Finally, $stmt->errno was checked against 0 (0 being no errors), to check that it was actually completed correctly.

Passing variables into a mysqli prepared statement

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();
}
?>

Parse error with php, syntax error, unexpected '$aircrafttype' (T_VARIABLE) [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I am getting a parse error with the following code. I have searched but could not find an answer.
error:
Parse error: syntax error, unexpected '$aircrafttype' (T_VARIABLE) in dbinput.php on line 58
Here is the code:
<?php
if (isset($_POST['submit'])) {
$data_missing = array();
if(empty($_POST['airline'])) {
$data_missing[] = 'Flygbolag';
} else {
$airline = $_POST['airline'];
}
if(empty($_POST['registration'])) {
$data_missing[] = 'Registrering';
} else {
$registration = $_POST['registration'];
}
if(empty($_POST['msn'])) {
$data_missing[] = 'MSN';
} else {
$msn = $_POST['msn'];
}
if(empty($_POST['aircrafttype'])) {
$data_missing[] = 'Flygplanstyp';
} else {
$aircrafttype = $_POST['aircrafttype'];
}
if(empty($_POST['enginedata'])) {
$data_missing[] = 'Motorer';
} else {
$enginedata = $_POST['enginedata'];
}
if(empty($_POST['loc'])) {
$data_missing[] = 'Plats';
} else {
$loc = $_POST['loc'];
}
}
if (empty($data_missing)) {
require_once('../dbconnect.php');
$query = "INSERT INTO Aircraft_spotted VALUES (?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "ssisss", $airline, $registration, $msn, $aircrafttype, $enginedata, $loc);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if ($affected_rows == 1) {
echo "Aircraft entered to database";
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
echo "Error occured: " . mysqli_error();
}
} else {
echo "You need to enter the following data: <br />";
foreach ($data_missing as $missing) {
echo "$missing<br />";
echo "string";
}
}
?>
I am grateful for any answer or help with the issue. Thanks a lot! Very much appreciate it!
Samuel
check if your $_POST['aircrafttype'] exists by print_r($_POST)
Probably you don't have set this or aircrafttype field is not sent to the POST. Try with:
if (isset($_POST['submit'])) {
$data_missing = array();
if(empty($_POST['airline']) || !isset($_POST['airline'])) {
$data_missing[] = 'Flygbolag';
} else {
$airline = $_POST['airline'];
}
if(empty($_POST['registration']) || !isset($_POST['registration'])) {
$data_missing[] = 'Registrering';
} else {
$registration = $_POST['registration'];
}
if(empty($_POST['msn']) || !isset($_POST['msn'])) {
$data_missing[] = 'MSN';
} else {
$msn = $_POST['msn'];
}
if(empty($_POST['aircrafttype']) || !isset($_POST['aircrafttype'])) {
$data_missing[] = 'Flygplanstyp';
} else {
$aircrafttype = $_POST['aircrafttype'];
}
if(empty($_POST['enginedata']) || !isset($_POST['enginedata'])) {
$data_missing[] = 'Motorer';
} else {
$enginedata = $_POST['enginedata'];
}
if(empty($_POST['loc']) || !isset($_POST['loc'])) {
$data_missing[] = 'Plats';
} else {
$loc = $_POST['loc'];
}
}

Looping correctly though array

Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.

Categories