PHP function errors not showing - php

I wasn't entirely sure how to search for this question, so if it has been asked before please send me in the right direction.
I have a validation function with an array. Inside my array I have set up errors to be displayed if one of the form fields doesn't validate. If the user fills a field out wrong, they should get an error of which field was wrong and the form should be still present. However, they get a blank page with only the generic error (the one I echo when I called the function) and not the field-specific error. Can someone please tell me where I went wrong?
$output_form = 1; //control if form displays - yes
$error_text = '';
//declare form elements (empty first load)
$fname = '';
$valid_fname = 0;
$fname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$fname_error_message = 'First name must be 2-15 alphabetic characters only.<br>';
$lname = '';
$valid_lname = 0;
$lname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$lname_error_message = 'Last name must be 2-15 alphabetic characters only.<br>';
$phone = '';
$valid_phone = 0;
$phone_regex = '/^\(\d{3}\)\d{3}-\d{4}$/';
$phone_error_message = 'Phone number must be in (xxx)xxx-xxxx format.<br>';
$city = '';
$valid_city = 0;
$city_regex = '/^([A-Z]|[a-z]){2,15}$/';
$city_error_message = 'City must be 2-15 alphabetic characters only.<br>';
$state = '';
$valid_state = 0;
$state_regex = '/^([A-Z]|[a-z]){2}$/';
$state_error_message = 'State must be 2 alphabetic characters only.<br>';
//data posted
if (isset($_POST['submit'])) {
if ($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}//end debug
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$phone = trim($_POST['phone']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$phone_replace = preg_replace('/[\(\)\-\s]/', '', $phone);
function validate_form($fields, &$errors = []) {
$errors = [];
foreach ($fields as $name => $field) {
if (!preg_match ($field['regex'], $field['value'])) {
$errors[$name] = $field['error'];
$output_form = 1;
}
}
return empty($errors); //returns true/false
}
$fields = [
'fname' => ['regex' => $fname_regex, 'value' => $fname, 'error' => $fname_error_message],
'lname' => ['regex' => $lname_regex, 'value' => $lname, 'error' => $lname_error_message],
'phone' => ['regex' => $phone_regex, 'value' => $phone, 'error' => $fname_error_message],
'city' => ['regex' => $city_regex, 'value' => $city, 'error' => $city_error_message],
'state' => ['regex' => $state_regex, 'value' => $state, 'error' => $state_error_message],
];
$errors = [];
if (!validate_form($fields, $errors)) {
echo "<p>One of your fields is invalid. Please check and re-submit.</p>";
$output_form = 1;
return (false);
}
else {
$output_form = 0;
}

foreach($errors as $error) echo "<p>$error</p>";
Actually outputting stuff usually helps ;)

Related

Json_encode strange behavior

I am experiencing some strange behavior when using json_encode.
This is my code:
if($_POST["action"] == 'profile')
{
sleep(2);
$error = '';
$success = '';
$admin_name = '';
$admin_contact_no = '';
$admin_email = '';
$admin_profile = '';
$data = array(
':admin_email' => $_POST["admin_email"],
':admin_id' => $_POST['hidden_id']
);
$visitor->query = "
SELECT * FROM admin_table
WHERE admin_email = :admin_email
AND admin_id != :admin_id
";
$visitor->execute($data);
if($visitor->row_count() > 0)
{
$error = '<div class="alert alert-danger">User Email Already Exists</div>';
}
else
{
$user_image = $_POST["hidden_user_image"];
if($_FILES["user_image"]["name"] != '')
{
$user_image = upload_image();
}
$admin_name = $visitor->clean_input($_POST["admin_name"]);
$admin_contact_no = $_POST["admin_contact_no"];
$admin_email = $_POST["admin_email"];
$admin_profile = $user_image;
$data = array(
':admin_name' => $admin_name,
':admin_contact_no' => $admin_contact_no,
':admin_email' => $admin_email,
':admin_profile' => $admin_profile
);
$visitor->query = "
UPDATE admin_table
SET admin_name = :admin_name,
admin_contact_no = :admin_contact_no,
admin_email = :admin_email,
admin_profile = :admin_profile
WHERE admin_id = '".$_POST['hidden_id']."'
";
$visitor->execute($data);
$success = '<div class="alert alert-success">User Details Updated</div>';
}
$output = array(
'error' => $error,
'success' => $success,
'admin_name' => $admin_name,
'admin_contact_no' => $admin_contact_no,
'admin_email' => $admin_email,
'admin_profile' => $admin_profile
);
echo json_encode($output);
}
Alert message for $error displays accordingly while alert message for $success does not.
If I swap positions between $error = '<div class="alert alert-danger">User Email Already Exists</div>'; and $success = '<div class="alert alert-success">User Details Updated</div>';, $error still works while $success still does not, which deeply confuses me.
I know I can avoid all this trouble by using echo, but I really want to find out what the issue is here.
Thank you for your help.
It was just a spelling error, wrote "succes" instead of "success".
I apologize for the trouble and thank you for your help.

How to insert multiple dynamic data using CodeIgniter?

I am using CodeIgniter, I am displaying the fields dynamically. Now I have to insert the data in the database. So I tried below code.
$order = $this->input->post('order[]');
$partner = $this->input->post('parner[]');
$bankname = $this->input->post('newpartner[]');
$status = $this->input->post('filestatus[]');
$user_id = $this->input->post('user_id');
$order_length = sizeof($order);
for ($j = 0; $j < $order_length; $j++) {
if (($status = 1) || ($status = 3)) {
$remark = $this->input->post('remark[]');
} else {
$remark = "";
}
if (($status = 2) || ($status = 4))) {
$reasonDate = $this->input-> post('reasonDate[]');
$remark = $this->input-> post('remark[]');
} else {
$reasonDate = "";
$remark = "";
}
if ($status = 7) {
$reasonAmt = $this->input->post('reasonAmt[]');
$reason = $this->input->post('reason[]');
} else {
$reasonAmt = "";
$reason = "";
}
$data['row'] = array(
'order' => $order[$j],
'bankname' => $bankname[$j],
'status' => $status[$j],
'lead_id' => $user_id,
'remark' => $remark[$j],
'reasonDate' => $reasonDate[$j],
'reasonAmt' => $reasonAmt[$j],
'reason' => $reason[$j]
);
$save = array(
'b_orderno' => $data['row']['order'],
'b_bankname' => $data['row']['bankname'],
'b_filestatus' => $data['row']['status'],
'p_id' => $data['row']['pid'],
'lead_id' => $data['row']['lead_id'],
'b_remark' => $data['row']['remark'],
'b_date' => $data['row']['reasonDate'],
'b_amt' => $data['row']['reasonAmt'],
'b_reason' => $data['row']['reason']
);
$afterxss = $this->security-> xss_clean($save);
if ($afterxss) {
$this - > db - > insert('tbl_bankdata', $afterxss);
$response['error'] = "true";
$response['msg'] = "added successfully";
} else {
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
}
echo json_encode($response);
I am getting the issue on the status field because depending upon the status value input field will display. Also, I used If the condition in logic for the status field. Each row has a unique status field.
You will find my HTML and script in below link.
https://jsfiddle.net/08phzue3/
This is my UI screenshot. Ignore the value that is only for testing purpose.
1)Onload this will display
2) If user select the status
3) If multiple row
Would you help me out with this?
Actually you are not comparing here:
if (($status = 1) || ($status = 3)) {
You are assigning the values to your $status variable
this should be:
if (($status == 1) || ($status == 3)) {
Side note: same for other conditions as well.
Edit:
As you mentioned you are getting array in $status so using comparison is not a correct logic here, there are multiple solution available,
You can use in_array() like:
if(in_array(1, $status) || in_array(3, $status)){
$remark = $this->input->post('remark[]');
}
else{
$remark = "";
}
Final Solutions (04-07-2019):
After changing the $save and $data arrays, issue has been resolved for OP:
$save['b_orderno'] = $order[$j];
$save['b_bankname'] = $bankname[$j];
$save['b_filestatus'] = $status[$j];
$save['p_id'] = $partner[$j];
$save['lead_id'] = $user_id;
if(!empty($remark[$j])){
$save['b_remark'] = $remark[$j];
}
if(!empty($reasonDate[$j])){
$save['b_date'] = $reasonDate[$j];
}
if(!empty($message[$j])){
$save['b_message'] = $message[$j];
}
if(!empty($reasonAmt[$j])){
$save['b_amt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$save['b_reason'] = $reason[$j];
}
$data['row']['order'] = $order[$j];
$data['row']['bankname'] = $bankname[$j];
$data['row']['status'] = $status[$j];
$data['row']['lead_id'] = $user_id;
$data['row']['remark'] = $remark[$j];
$data['row']['reasonDate'] = $reasonDate[$j];
if(!empty($reasonAmt[$j])){
$data['row']['reasonAmt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$data['row']['reason'] = $reason[$j];
}

CI: Argument Count Error

I'm working on a project & I've encounter with this problem "Argument Count Error". I've checked code by code but did not find anything.
Controller Code:
public function new_package(){
$name = $this->input->post('name');
$price = $this->input->post('price');
$description = $this->input->post('description');
if($name != '' && $price != '' && $description != ''){
$packageData = $this->Process->package_add($name, $price, $description);
if($packageData){
$added = "Package Added";
$this->session->set_flashdata('added', $added);
redirect('Packages');
}
}
else{
$blank = "Please Fill Required Fields.";
$this->session->set_flashdata('blank', $blank);
redirect('Packages');
}
}
Modal Code:
public function package_add($name, $price, $description){
$insertData = array(
'title' => $name,
'price' => $price,
'description' => $description
);
$insertQuery = $this->db->insert('packages', $insertData);
if($insertQuery){
return TRUE;
}
else{
return FALSE;
}
}
Modal name Process.
Error: ""Type: ArgumentCountError
Message: Too few arguments to function Process::package_add(), 0
passed in
C:\xampp\htdocs\apn_new\backend\application\controllers\Packages.php
on line 32 and exactly 3 expected
Filename:
C:\xampp\htdocs\apn_new\backend\application\models\Process.php
Line Number: 299""
I've search over this site related this type problem but I did not find my problem solution. This problem comes before submit form. Please Help me.
Thank You
Create insert array in controller
Controller.php
public function new_package(){
$name = $this->input->post('name');
$price = $this->input->post('price');
$description = $this->input->post('description');
if($name != '' && $price != '' && $description != ''){
$insertData = array(
'title' => $name,
'price' => $price,
'description' => $description
);
$packageData = $this->Process->package_add($insertData);
if($packageData){
$added = "Package Added";
$this->session->set_flashdata('added', $added);
redirect('Packages');
}
}
else{
$blank = "Please Fill Required Fields.";
$this->session->set_flashdata('blank', $blank);
redirect('Packages');
}
}
Model.php
public function package_add($insertData){
$insertQuery = $this->db->insert('packages', $insertData);
if($insertQuery){
return TRUE;
}
else{
return FALSE;
}
}

Get data from $_SESSION

I'm trying to create simple server side validation, this is my method
public function create() {
$name = $_POST['name'];
session_start();
unset($_SESSION['errors']);
$count = $this->model->checkIfUserExists($name);
if($count > 0) {
$_SESSION['errors'] = array(
'message' => 'User Already Exists',
'variables' => array(
'name' => $_POST['name'],
'password' => $_POST['password'],
),
);
header('location: ' . URL . 'user/registration');
exit;
}
$data = array();
$data['name'] = $_POST['name'];
$data['password'] = $_POST['password'];
$this->model->create($data);
header('location: ' . URL);
}
and below code from registration.php
<?php
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>
but I got errors
Warning: Illegal string offset 'message' in C:\xampp\htdocs\test\views\user\registration.php on line 6
�
Notice: Undefined index: message in C:\xampp\htdocs\test\views\user\registration.php on line 6
How to fix it?
Generally, Warning: Illegal string offset ... means that you are trying to access a string as an array.
Currently, you are setting $_SESSION['errors'] to an associative array with two elements, message and variables. I believe what you are trying to achieve is to create an array with multiple errors that each have a message and variables.
Setting it like this should do:
...
$_SESSION['errors'] = array();
if ($count > 0) {
$_SESSION['errors'][] = array(
'message' = > 'User Already Exists',
'variables' = > array(
'name' = > $_POST['name'],
'password' = > $_POST['password'],
),
);
header('location: '.URL.'user/registration');
exit;
}
...
The empty square brackets add a new element to the array:
$myArray[] = $myNewElement;
This way you can easily add additional errors to the list:
$_SESSION['errors'][] = array(
'message' = > 'Error two',
'variables' = > array(...),
);
$_SESSION['errors'][] = array(
'message' = > 'Error three',
'variables' = > array(...),
);
It's because foreach goes throught items in main array. ["message", "variables"]
Assign $_SESSION['errors'] = like this: $_SESSION['errors'][] =
$_SESSION['errors'][] = array(
'message' => 'User Already Exists',
'variables' => array(
'name' => $_POST['name'],
'password' => $_POST['password'],
),
);
registration.php at first start session session_start()
<?php
session_start();
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>

Laravel validator 'in' issue for numbers in input

I need help in fixing an issue in which I am using laravel 'in' validator to match a given input against multiple comma separated string of values. Now the issue is when there is a number in the input and it does not matches with any of the comma separated values then it gives an exception:
preg_match() expects parameter 2 to be string, array given
However it should simply give error message in validator object that input field does not match. instead it gives above mentioned exception. Following is my code:
if (!empty($program)) {
$institution_id = $program->InstitutionId;
$roster_users = $program->usersRosters()->where('ProfileType', 'Student')->get();
if (!empty($roster_users)) {
$rostered_users_ids = implode(',', $roster_users->lists('id'));
}
if (!empty($roster_users)) {
$rostered_users_usernames = implode(',', $roster_users->lists('UserName'));
}
$teacher_roster_users = $program->usersRosters()->where('ProfileType', 'External Staff')->get();
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_usernames = implode(',', $teacher_roster_users->lists('UserName'));
}
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_data = $teacher_roster_users->lists('id', 'UserName');
}
}
$rules = [
'aasectionname.required' => '501 – AA section does not exist',
'aaid' => 'numeric|exists:users,id|in:' . $rostered_users_ids . '|aaidinstitutionmismatch:' . $institution_id,
'institutionid' => 'numeric|in:' . $institution_id,
'username' => 'exists:users,UserName|in:' . $rostered_users_usernames . '|usernameinstitutionmismatch:' . $institution_id,
'schoolid' => 'numeric',
'groupowner' => 'in:'.$teacher_rostered_users_usernames,
'remove' => 'in:0,1'
];
$messages = [
// InstitutionId
'institutionid.numeric' => '101 – Invalid Institution ID',
'institutionid.in' => '102 – Institution ID does not match Program',
// Usernames
'username.exists' => '201 – UserName does not exist',
'username.in' => '202 – UserName is not rostered to this program',
'username.usernameinstitutionmismatch' => '203 – User/Institution Mismatch - UserName is not assigned to this Institution',
// AAId
'aaid.numeric' => '301 – AA ID does not exist',
'aaid.exists' => '301 – AA ID does not exist',
'aaid.in' => '302 – AA ID is not rostered to this program',
'aaid.aaidinstitutionmismatch' => '303 – AA ID/Institution Mismatch – AAID is not assigned to this Institution',
// Mismatch
'bothmismatch' => '401 – AAID/UserName/SchoolID do not match (This is a combination of at least 2 of these items)',
// Teacher
'groupowner.in' => '501 – GroupOwner does not exist',
// Remove
'remove' => '601 – No Student record match to remove',
];
Excel::load($file, function($excel) use($program, $rules, $messages, $errors, &$errors_data, $teacher_rostered_users_data) {
global $totalmismatch;
$results = $excel->get();
$program_group_model = new ProgramGroup;
$option_model = new Option;
$group_default_status_id = key($option_model->getProgramsStatus(['Active']));
$groupVisibilityStatusId = $group_type = $option_model->getVisibilityOptions('Question Visibility','Private');
$data = [];
$lastSecId = null;
$groupSectionPreviousName = null;
$groupname = null;
$data['status'] = $group_default_status_id;
$data['program_id'] = $program->Id;
$groupname_lists = $program_group_model->with(['programs' => function ($query) use ($program){
$query->where('ProgramId','=',$program->Id);
}])->get()->lists('Name','Id');
foreach ($results as $key => $row) {
$inputs = $row->toArray();
$groupname = trim($inputs['usergroup']);
$errors = [];
// Stop reading the excel when aasectionname is empty
if (empty($groupname) || $groupname == null) {
$errors['remove'] = $messages['aasectionname.required'];
}
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages()->toArray();
foreach ($errors as $error) {
foreach ($error as $e) {
$errors_data[] = [$key + 2, $e];
}
}
} else {
$aaid = intval($inputs['aaid']);
$groupowner_name = $inputs['groupowner'];
if (!empty($teacher_rostered_users_data[$groupowner_name])) {
$groupowner_id = $teacher_rostered_users_data[$groupowner_name];
$data['owner'] = $groupowner_id;
}
$remove = intval($inputs['remove']);
// Remove existing Student Roster
if (!empty($remove)) {
$removed = false;
$user_ids = is_array($aaid) ? $aaid : [$aaid];
$program_group = $program->programGroups()->where('Name', $groupname);
if (!empty($program_group)) {
$program_group = $program_group->first();
}
if (!empty($program_group)) {
$program_group = $program_group->users();
}
if (!empty($program_group) && !empty($user_ids)) {
$removed = $program_group->detach($user_ids);
}
if (!$removed) {
$errors['remove'] = $messages['remove'];
}
} else {
if (!in_array($groupname, $groupname_lists) || $groupSectionPreviousName != $groupname) {
$data['name'] = $groupname;
$data['group_id'] = array_search($groupname, $groupname_lists);
$data['group_type'] = $groupVisibilityStatusId;
$sectionId = $program_group_model->saveProgramGroup($data);
$data[$sectionId]['selected'][] = $aaid;
$groupname_lists[$sectionId] = $groupname;
} else {
$temp = array_flip($groupname_lists);
$data[$temp[$groupname]]['selected'][] = $aaid;
}
}
if ($totalmismatch === 2) {
$errors['bothmismatch'] = $messages['bothmismatch'];
}
foreach ($errors as $error) {
$errors_data[] = [$key + 2, $error];
}
}
$groupSectionPreviousName = $groupname;
}
$programAASectionModelForSectionUsers = new ProgramSectionUser();
$programAASectionModelForSectionUsers->saveProgramGroupUsers($data);
});
$rules
array:7 [
"aasectionname.required" => "501 – AA section does not exist"
"aaid" => "numeric|exists:users,id|in:28,29,32,33,25,24,27|aaidinstitutionmismatch:42"
"institutionid" => "numeric|in:42"
"username" => "exists:users,UserName|in:Kabeer,Ayaz,fddesaaweqq,fdawerascvdfc,haseeb,kamran,shahid|usernameinstitutionmismatch:42"
"schoolid" => "numeric"
"groupowner" => "in:externalstaff,rahat,uzma,sahar,haseebahmad,saimariaz,fredrick"
"remove" => "in:0,1"
]

Categories