Codeigniter error inserting array in db - php

I am currently making a registration form where you could register by batch but i am getting an error
Error Number: 1054
Unknown column 'test#gmail.com' in 'field list'
INSERT INTO user (date_registered, test#gmail.com) VALUES (NOW(), '')
my code is
controller
public function registerbatch(){
for ($i = 0; $i < count($this->input->post('surname','firstname','age','school','course','email')); $i++) {
$this->form_validation->set_rules("surname[$i]", "surname[$i]", "required");
$this->form_validation->set_rules("firstname[$i]", "firstname[$i]", "required");
$this->form_validation->set_rules("age[$i]", "Age[$i]", "required");
$this->form_validation->set_rules("school[$i]", "School[$i]", "required");
$this->form_validation->set_rules("course[$i]", "Course[$i]", "required");
$this->form_validation->set_rules("email[$i]", "Email[$i]", "required");
}
if ($this->form_validation->run() == TRUE) {
$reg_dat_multi = $this->input->post('surname');
$reg_dat_multi = $this->input->post('name');
$reg_dat_multi = $this->input->post('age');
$reg_dat_multi = $this->input->post('school');
$reg_dat_multi = $this->input->post('course');
$reg_dat_multi = $this->input->post('email');
foreach ($reg_dat_multi as $reg_dat) {
$this->user_model->add_batchuser($reg_dat);
}
$this->load->view('user/home_view');
} else {
$this->load->view('user/batch_register');
}
}
for view
<html>
<head>
</head>
<body>
<form class="form" action="<?php echo base_url() . 'user/registerbatch'; ?>" method="post" class="form-horizontal" role="form">
<?php for ($i = 0; $i < $num; $i++): ?>
<br>
Surname: <input type="text" name="surname[]">
<br>
Name: <input type="text" name="firstname[]">
<br>
Age:<input type ="int" name ="age[]">
<br>
School: <input type="text" readonly value="<?= $school ?>" name="school[]">
<br>
Course:<input type ="text" name ="course[]">
<br>
Email:<input type ="text" name ="email[]">
<br>
<br>
<?php endfor ?>
<button type="submit" class="btn btn-success">Register</button>
</body>
</html>
and model
public function add_batchuser($reg_dat) {
$this->db->set('date_registered', 'NOW()', FALSE);
$this->db->insert('user', $reg_dat);
}

Why not use insert_batch of codeigniter?
Example in the docs:
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
for your Use Case assuming you had the same number of surname, firstname, and all of the inputs you can foreach to create an array then add use the insert_batch:
public function add_batchuser($reg_dat) {
foreach ($reg_dat[firstname] as $key => $value) {
$details[$key]['firstname'] = $reg_dat['firstname'][$key];
$details[$key]['surname'] = $reg_dat['surname'][$key];
$details[$key]['age'] = $reg_dat['age'][$key];
$details[$key]['course'] = $reg_dat['course'][$key];
$details[$key]['email'] = $reg_dat['email'][$key];
$details[$key]['date_registered'] => $this->database_now_time();
}
$this->db->insert_batch('user', $details);
}
please remove the:
foreach ($reg_dat_multi as $reg_dat) {
$this->user_model->add_batchuser($reg_dat);
}
you can just use:
$reg_dat_multi = $this->input->post(null, true); //This will get all the data in post parameters
$this->user_model->add_batchuser($reg_dat_multi);

Related

wordpress insert post doesnt work on edge

I create a code to save data from Form to custom_post_type.
Everything ok on Firefox but when I test it on edge, the post still save, but I can't edit the post on admin, or view the post(object not found) (see the image)
I really don't know where is the problem, please help.
this is my code, i copy it from my function.php:
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
?>
<div>
<div>
RESERVATION
</div>
<form id="new_post" class = 'datcho' name="new_post" method="post">
<input type = 'text' name = 'ten' required>
<input type = 'tel' name = 'sdt' required>
<input type = 'number' name = 'num' min='1' max = '10' required>
<input type = 'date' name = 'ngay' required>
<input type = 'time' name = 'time' value = '13:00' min='9:00' max='21:00' required>
<?php wp_nonce_field( 'wps-frontend-post' ); ?>
<input type="submit" value="Reservation" id="submit" name="submit"/>
</div>
</form>
</div>
<?php
}
function wpshout_save_post_if_submitted() {
// Stop running function if form wasn't submitted
if ( !isset($_POST['ten']) ) {
return;
}
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
echo 'Did not save because your form seemed to be invalid. Sorry';
return;
}
// Do some minor form validation to make sure there is content
// Add the content of the form to $post as an array
$title = wp_strip_all_tags($_POST['ten']);
$post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'Pending',
'post_type' => 'datcho'
);
$eror = wp_insert_post($post,true);
if($eror){
$sdt = wp_strip_all_tags($_POST['sdt']);
$ngay = wp_strip_all_tags($_POST['ngay']);
$time = wp_strip_all_tags($_POST['time']);
$num = wp_strip_all_tags($_POST['num']);
add_post_meta($eror, 'sdt', $sdt);
add_post_meta($eror, 'ngay', $ngay);
add_post_meta($eror, 'time', $time);
add_post_meta($eror, 'num', $num);
echo 'Saved your post successfully! :)';
}else {
echo "something wrong";
}
}
Here is the complete solution.
The issue mainly is you are not logged into the WP in Edge so when creating the post using wp_insert_post wordpress has no idea with which account should it attach that post.
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
?>
<div>
<div>
RESERVATION
</div>
<form id="new_post" class = 'datcho' name="new_post" method="post">
<input type = 'text' name = 'ten' required>
<input type = 'tel' name = 'sdt' required>
<input type = 'number' name = 'num' min='1' max = '10' required>
<input type = 'date' name = 'ngay' required>
<input type = 'time' name = 'time' value = '13:00' min='9:00' max='21:00' required>
<?php wp_nonce_field( 'wps-frontend-post' ); ?>
<input type="submit" value="Reservation" id="submit" name="submit"/>
</form>
</div>
<?php
}
function wpshout_save_post_if_submitted() {
// Stop running function if form wasn't submitted
if ( !isset($_POST['ten']) ) {
return;
}
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
echo 'Did not save because your form seemed to be invalid. Sorry';
return;
}
// Do some minor form validation to make sure there is content
// Add the content of the form to $post as an array
$title = wp_strip_all_tags($_POST['ten']);
$author_id = 1; // You can change it with your User ID
$post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_type' => 'datcho'
'post_author' => $author_id
);
$eror = wp_insert_post($post,true);
if($eror){
$sdt = wp_strip_all_tags($_POST['sdt']);
$ngay = wp_strip_all_tags($_POST['ngay']);
$time = wp_strip_all_tags($_POST['time']);
$num = wp_strip_all_tags($_POST['num']);
add_post_meta($eror, 'sdt', $sdt);
add_post_meta($eror, 'ngay', $ngay);
add_post_meta($eror, 'time', $time);
add_post_meta($eror, 'num', $num);
echo 'Saved your post successfully! :)';
}else {
echo "something wrong";
}
}

How can i insert multiple rows each of which has an array?

I need to insert data from multiple rows. And each of these rows has an array on the third column, Class. I want to insert it such that the data in the database will look like that shown on the MYSQL screenshot below. The error I am having is that the class column inserts a duplicate data instead..
<script>
var rowCount = 1;
function addMoreRows(frm){
rowCount ++;
var inputer = '<div class="row rowCount'+rowCount+'"><div class="col-md-3"> <div class="form-group"><input type="text" class="form-control" name="subject[]"></div></div><div class="col-md-3"> <div class="form-group"><input type="text" class="form-control" name="highest_mark_obtainable[]"></div></div><div class="col-md-3"><div class="form-group"><select class="form-control" name="class[]"><?php foreach($class_rows as $class_row){echo'<option value="'.$class_row['group'].'">'.$class_row['class'].'</option>';}?></select></div></div><div class="col-md-2"><button class="btn btn-danger" onclick="removeRow('+rowCount+')"><i class="fa fa-minus"></i> Remove row</button></div></div>';
$('.gra-grp-row').append(inputer);
}
function removeRow(removeNum){
$('.rowCount'+removeNum).remove();
}
</script>
Below is my model
public function create_subject(){
$subject = $this->input->post('subject');
$highest_mark_obtainable = $this->input->post('highest_mark_obtainable');
$classes[] = implode(',', $this->input->post('class'));
for($i = 0; $i < count($subject); $i++){
for($p = 0; $p < count($classes); $p++){
$new_subject = array(
'subject' => $subject[$i],
'highest_mark_obtainable' => $highest_mark_obtainable[$i],
'class' => $classes[$p],
'username' => $this->session->userdata('username')
);
$this->db->insert('subject', $new_subject);
}
}
return TRUE;
}
}
Below is my controller
public function create_subject(){
$this->output->enable_profiler(TRUE);
if($this->input->is_ajax_request() && $this->input->post('ajax') == 1){
$this->form_validation->set_rules('subject[]', 'Subject',
'trim|required|min_length[2]|max_length[50]');
$this->form_validation->set_rules('highest_mark_obtainable[]', 'Maximum `enter code here`marks obtainable', 'trim|required|numeric');
$this->form_validation->set_rules('class[]', 'Class', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->output->set_status_header('400');
echo '<span class="admin_validation_error" `enter code here`style="color:#ff0000">'.validation_errors().'</span>';
} else {
if($this->subject_model->create_subject() == true){
echo '<span class="validation_success" style="color:green; font- weight:bolder">Well done! Subject(s) successfully created.</span>';
}
}
}else{
redirect('errors/not_found');
}
} `
BELOW IS THE FORM
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="Subject">Subject<span class="asterix"> *</span></label>
<input type="text" class="form-control" name="subject[]" id="" placeholder="Mathematics" value="">
</div>
</div><!--Subject-->
<div class="col-md-4">
<div class="form-group">
<label for="Highest mark obtainable">Maximum marks obtainable<span
`class="asterix"> *</span></label>
<input type="text" class="form-control" name="highest_mark_obtainable[]"
id="" placeholder="100" value="">
</div>
</div><!--Highest mark obtainable-->
<div class="col-md-3">
<div class="form-group">
<label for="Class">Classes that do subject<span class="asterix"> *</span>
</label> <select class="form-control select2subjects" name="class[]" ` `multiple="multiple" style="width:100%">
<?php foreach ($class_rows as $class){
echo '<option value="'.$class['class'].'">'.$class['class'].'</option>';
}
?>
</select>
</div>
</div><!--class associated with subject-->
<div class="col-md-2">
</div>
</div>
Im not sure if your using Codeigniter 3 and im not sure if this function is exclusive to Codeginiter 3
You could use the function in the query builder $this->db->insert_batch()
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
A further explanation here:
https://codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder#inserting-data
$classes = $this->input->post('class');
for($i = 0; $i < count($subject); $i++) {
$new_subject = array(
'subject' => $subject[$i],
'highest_mark_obtainable' => $highest_mark_obtainable[$i],
'class' => implode(',', $classes[$i]),
'username' => $this->session->userdata('username')
);
$this->db->insert('subject', $new_subject);
}

Codeigniter- How to preserve form values if error on submit

I have the form field like
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php if($user->postal_code === NULL) { echo set_value('postal_code');} else { echo $user->postal_code;} ?>">
<label for="form_control_1">Postal Code</label>
<span class="help-block">Postal Code is required</span>
and my function is
public function postProfile() {
if ($_POST) {
$this->form_validation->set_rules('postal_code', 'Postal Code', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('month', 'Month', 'required');
$this->form_validation->set_rules('day', 'Day', 'required');
$this->form_validation->set_rules('year', 'Year', 'required');
$this->form_validation->set_rules('mobile_number', 'Mobile Number', 'required');
if ($this->form_validation->run() === FALSE) {
//$this->session->set_flashdata('err', validation_errors());
$this->session->set_flashdata('email_err', form_error('email'));
$this->session->set_flashdata('postal_code_err', form_error('postal_code'));
$this->session->set_flashdata('gender_err', form_error('gender'));
$this->session->set_flashdata('country_err', form_error('country'));
$this->session->set_flashdata('day_err', form_error('day'));
$this->session->set_flashdata('year_err', form_error('year'));
$this->session->set_flashdata('month_err', form_error('month'));
$this->session->set_flashdata('mobile_err', form_error('mobile_number'));
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
$dob = $this->input->post('month') . '/' . $this->input->post('day') . '/' . $this->input->post('year');
$userData = array(
'email' => $this->input->post('email'),
'date_of_birth' => $dob,
'gender' => $this->input->post('gender'),
'country' => $this->input->post('country'),
'mobile_number' => $this->input->post('mobile_number'),
'postal_code' => $this->input->post('postal_code'),
);
$updateUser = $this->user->updateUser($this->session->userdata['front']['id'], $userData);
if ($updateUser) {
$this->session->set_flashdata('err', '<div class="alert alert-success">Profile Updated Successfuly</div>');
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
echo "Un expected error ";
exit;
}
}
} else {
$this->logout();
}
}
but value is not shown for the postal code field in case of validation errors
When error occur then you need to render view instead of rediect().
if ($this->form_validation->run() == FALSE) {
// no need to set_flashdata here for form_error()
$this->load->view('view_form',$data);
return;
}else{
//success code
}
Now view file
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php echo set_value('postal_code');?>">
<?php echo form_error('postal_code','<p class="alert alert-danger">','</p>');?>
Now your form will repopulate previous data if any error occur. In the same time you will see error message under your postal_code field
You can set these values in flashdata and redirect to your form. For example
if ($this->form_validation->run() == FALSE) {
$data = array(
'errors' => validation_errors(),
'name' => $this->input->post('name')//check this
);
$this->session->set_flashdata($data);
redirect('YOUR-URL-HERE');
}
And in your form use value attribute of form input as given below
<input type="text" class="form-control" name="name" placeholder="Name" value="<?= $this->session->flashdata('name'); ?>">

Codeigniter insert array into database

I am currently making a registration form where in you could register individually or by many I need a way how to make the multiple register work i cant add the input into db i get an array to string conversion error
i still dont have the model for this
my code is
controller
public function registerbatch(){
for ($i = 0; $i < count($this->input->post('surname','firstname','age','school','course','email')); $i++) {
$this->form_validation->set_rules("surname[$i]", "surname[$i]", "required");
$this->form_validation->set_rules("firstname[$i]", "firstname[$i]", "required");
$this->form_validation->set_rules("age[$i]", "Age[$i]", "required");
$this->form_validation->set_rules("school[$i]", "School[$i]", "required");
$this->form_validation->set_rules("course[$i]", "Course[$i]", "required");
$this->form_validation->set_rules("email[$i]", "Email[$i]", "required");
}
if ($this->form_validation->run() == TRUE) {
$reg_dat = array(
'surname' => $this->input->post('surname'),
'name' => $this->input->post('firstname'),
'age' => $this->input->post('age'),
'school' => $this->input->post('school'),
'course' => ($this->input->post('course')),
'email' => ($this->input->post('email')),
);
$this->user_model->add_user($reg_dat);
$this->load->view('user/home_view');
} else {
$this->load->view('user/batch_register');
}
view:
<html>
<head>
</head>
<body>
<form class="form" action="<?php echo base_url() . 'user/registerbatch'; ?>" method="post" class="form-horizontal" role="form">
<?php for ($i = 0; $i < $num; $i++): ?>
<br>
Surname: <input type="text" name="surname[]">
<br>
Name: <input type="text" name="firstname[]">
<br>
Age:<input type ="int" name ="age[]">
<br>
School: <input type="text" readonly value="<?= $school ?>" name="school[]">
<br>
Course:<input type ="text" name ="course[]">
<br>
Email:<input type ="text" name ="email[]">
<br>
<br>
<?php endfor ?>
<button type="submit" class="btn btn-success">Register</button>
</body>
</html>
Try this below coding ....
if ($this->form_validation->run() == TRUE) {
extract($_POST);
foreach($surname as $key=>$value) {
$reg_dat = array(
'surname' => $value,
'name' => $firstname[$key],
'age' => $age[$key],
'school' => $school[$key],
'course' => $course[$key],
'email' => $email[$key],
);
$this->user_model->add_user($reg_dat);
}
}
$this->load->view('user/home_view');
Seems that your Post can be a multidimensional array. I think the best way to solve your problem is to foreach that post and insert every row
//your controller
if ($this->form_validation->run() == TRUE) {
$reg_dat_multi = $this->input->post();
foreach ($reg_dat_multi as $reg_dat) {
$this->user_model->add_user($reg_dat);
}
);
you didn't show your model but let's think that is something like this
//your model
function add_user($reg_dat){
if ( $this->db->insert('table', $reg_dat) ){
return true;
}
return false;
}
hope that helps

Trying to create a generalized function in PHP 5.2, error message not showing

Hi I am Trying to create a generalized function in PHP 5.2 and I am not able to get the error message to show. I am not sure on how I am to pass the variables to the validate function. How do I create an input variable equal to all input fields? Do I need to put all the inputs into an array? This may be a simple question for the experienced php programmers, for me I am still wrapping my head around everything php. I have included my code below. Thanks:
<?php
$debug=1;
$output_form= true;
//$valid_ = 0;
//$error_text= "";
function validateFormInput($input, $patterns, &$errors)
{
$valid_ = false;
$new = false;
foreach($input as $key => $value) {
if(!preg_match($patterns[$key], $value, $match)) {
$new[$key] = $errors[$key];
//$output_form = false;
}
// Remove errors if validation is made
else
unset($errors[$key]);
$valid_= true;
//$output_form = true;
}
//$output_form = false;
return $new;
}
//initialization
$inputs = array(
"fname" => '',
"lname" => '',
"phone" => '',
"city" => '',
"state" => '',
);
$patterns = array(
"fname" => '/^[a-zA-Z]{2,15}$/',
"lname" => '/^[a-zA-Z]{2,15}$/',
"phone" => '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/',
"city" => '/^[a-zA-Z]{3,20}$/',
"state" => '/^[a-zA-Z]{2}$/',
);
$errors = array(
"fname" => "Please enter your FIRST name between 2 and 15 letters.",
"lname" => "Please enter your LAST name between 2 and 15 letters.",
"phone" => "Please enter your phone number in (###)###-### format.",
"city" => "Please enter your city name between 3 and 20 letters.",
"state" => "Please enter your state's abbreviation (Example: CA).",
);
if(isset($_POST['submit'])) {
if ($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
//echo "<pre>";
//print_r($_FILES);
//echo "</pre>";
//die("temp stop point");
} //debug only
$fname=trim($_POST['fname']);
$lname=trim($_POST['lname']);
$phone=trim($_POST['phone']);
$city=trim($_POST['city']);
$state=trim($_POST['state']);
$inputs = $_POST;
//$output_form = false;
// Just unset the submit and pass the $_POST via $inputs
unset($inputs['submit']);
//$output_form = false;
validateFormInput($inputs,$patterns,$errors);
//$output_form = false;
if($errors)
echo implode("<br />",$errors);
$mobile = preg_replace('/\D+/', '', $phone);
$output_form = false;
}
//if ($valid_) {$output_form =false;}
//$not_valid = validateFormInput($inputs,$patterns,$errors);
//if($not_valid)
//echo implode("<br />",$not_valid);
//$output_form = false;
//else { $output_form = false;}
?>
?>
<!DOCTYPE html>
<html>
<head>
<title>Lesson 7</title>
<meta charset="UTF-8">
<meta name="description" content="php">
<meta name="keywords" content="php">
<meta name="author" content="William Payne">
<link rel="stylesheet" type="text/css" href="xxxxxxxxxxxx">
</head>
<body>
<div class="formLayout">
<?php
//form
if ($output_form) {
?>
<form action="<?=htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Info</legend>
<?=$error_text ?>
<label>First Name:</label><input name="fname" type="text" value="<?=$fname; ?>"><br>
<label>Last Name:</label><input name="lname" type="text" value="<?=$lname; ?>"><br>
<label>Phone Number:</label><input name="phone" type="text" value="<?=$phone; ?>"><br>
<label>City:</label><input name="city" type="text" value="<?=$city; ?>"><br>
<label>State:</label><input name="state" type="text" value="<?=$state; ?>"><br>
</fieldset>
<input name="submit" id="submit" type="submit" value="submit"><br>
</form>
<?php
} else {
//replace_mobile();
//Processing for database inclusion, email cofirmation can also go here, thank you
//2nd way to Solve Not using regex preg_replace $p = $phone; <?="$p[1]$p[2]$p[3]$p[5]$p[6]$p[7]$p[9]$p[10]$p[11]$p[12]";//
?>
<p><strong><?="$welcome_msg"; ?></strong></p>
<p><strong><?="$lname".''.', '. "$fname";?></strong></p>
<p><strong><?="$phone".''.', '."$mobile";?></strong></p>
<p><strong><?="$city".''.', '."$state";?></strong></p>
<?php
} //end if/else form output
?>
</div>
</body>
</html>
Further to my comment, here is what I meant by passing the variables as an array then looping over them, applying your patterns, and passing $errors by reference:
$patterns = array(
"fname" => '/^[a-zA-Z]{2,15}$/',
"lname" => '/^[a-zA-Z]{2,15}$/',
"phone" => '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/',
"city" => '/^[a-zA-Z]{3,20}$/',
"state" => '/^[a-zA-Z]{2}$/',
);
$errors = array(
"fname" => "Please enter your FIRST name between 2 and 15 letters.<br>",
"lname" => "Please enter your LAST name between 2 and 15 letters.<br>",
"phone" => "Please enter your phone number in (###)###-### format.<br>",
"city" => "Please enter your city name between 3 and 20 letters.<br>",
"state" => "Please enter your state's abbreviation (Example: CA).<br>",
);
// Pass by ref--------------------------------vv
function validateFormInput($input, $patterns, &$errors)
{
$new = false;
foreach($input as $key => $value) {
if(preg_match($patterns[$key], $value, $match))
unset($errors[$key]);
}
return (empty($errors));
}
$valid = false;
if(isset($_POST['submit'])) {
$inputs = $_POST;
unset($inputs['submit']);
$valid = validateFormInput($inputs,$patterns,$errors);
if(!empty($errors))
echo implode("<br />",$errors);
}
if(!$valid) {
?>
<form method="post">
<input type="text" name="fname" value="Name" />
<input type="text" name="lname" value="LastName" />
<input type="text" name="phone" value="123-123-1233" />
<input type="text" name="city" value="Reno" />
<input type="text" name="state" value="NsrV" />
<input type="submit" name="submit" value="submit" />
</form>
<?php }
EDIT: Based on your full code, I have revised the solution to be more comprehensive. All functions should be on their own pages and included at the top like include(__DIR__."/functions/function.validateFormInput.php"); (ideally setting up and autoloader function for even more simplicity) This will help keep the page clean:
define("ERRMODE",true);
function validateFormInput($input)
{
$errors = false;
foreach($input as $key => $value) {
$pattern = patternList($key);
if(!$pattern)
continue;
if(!preg_match($pattern, trim($value), $match)) {
$errors[$key] = errorMsg($key);
}
}
return $errors;
}
function patternList($name = false)
{
$patterns = array(
"fname" => '/^[a-zA-Z]{2,15}$/',
"lname" => '/^[a-zA-Z]{2,15}$/',
"phone" => '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/',
"city" => '/^[a-zA-Z]{3,20}$/',
"state" => '/^[a-zA-Z]{2}$/',
);
return (isset($patterns[$name]))? $patterns[$name]:false;
}
function errorMsg($name = false)
{
$errors = array(
"fname" => "Please enter your FIRST name between 2 and 15 letters.",
"lname" => "Please enter your LAST name between 2 and 15 letters.",
"phone" => "Please enter your phone number in (###)###-### format.",
"city" => "Please enter your city name between 3 and 20 letters.",
"state" => "Please enter your state's abbreviation (Example: CA).",
);
return (isset($errors[$name]))? $errors[$name]:false;
}
function printPre($val = false)
{
ob_start();
echo "<pre>";
print_r($_POST);
echo "</pre>";
$data = ob_get_contents();
ob_end_clean();
return $data;
}
if(isset($_POST['submit'])) {
if(ERRMODE) {
echo printPre($_POST);
echo printPre($_FILES);
}
$errors = validateFormInput($_POST);
$formValid = (empty($errors));
$fname = htmlspecialchars($_POST['fname']);
$lname = htmlspecialchars($_POST['lname']);
$phone = htmlspecialchars($_POST['phone']);
$city = htmlspecialchars($_POST['city']);
$state = htmlspecialchars($_POST['state']);
$mobile = preg_replace('/\D+/', '', $phone);
}
?><!DOCTYPE html>
<html>
<head>
<title>Lesson 7</title>
<meta charset="UTF-8">
<meta name="description" content="php">
<meta name="keywords" content="php">
<meta name="author" content="William Payne">
<link rel="stylesheet" type="text/css" href="xxxxxxxxxxxx">
</head>
<body>
<div class="formLayout">
<?php
//form
if (empty($formValid)) {
if(!empty($errors))
echo implode("<br />",$errors);
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Info</legend>
<?php echo $error_text ?>
<label>First Name:</label><input name="fname" type="text" value="<?php echo (!empty($fname))? $fname : ""; ?>"><br>
<label>Last Name:</label><input name="lname" type="text" value="<?php echo (!empty($lname))? $lname : ""; ?>"><br>
<label>Phone Number:</label><input name="phone" type="text" value="<?php echo (!empty($phone))? $phone : ""; ?>"><br>
<label>City:</label><input name="city" type="text" value="<?php echo (!empty($city))? $city : ""; ?>"><br>
<label>State:</label><input name="state" type="text" value="<?php echo (!empty($state))? $state : ""; ?>"><br>
</fieldset>
<input name="submit" id="submit" type="submit" value="submit"><br>
</form>
<?php
} else {
?>
<p><strong><?php echo "$welcome_msg"; ?></strong></p>
<p><strong><?php echo "{$lname}, {$fname}";?></strong></p>
<p><strong><?php echo "{$phone}"; ?></strong></p>
<p><strong><?php echo "{$city}, {$state}"; ?></strong></p>
<?php
}
?>
</div>
</body>
</html>
You may do it like this:
PHP:
// Errors array.
$errArray = [];
//function
function validateFormInput($input, $fieldName, $isRequired, $min, $max, $patterns, $example = '') {
// Trimming the input to get rid of empty spaces on the sides
$input = trim($input);
// If the provided value of required == 'yes', and variable is -
// empty add an error to the errors array.
if($isRequired == 'yes' && empty($input)){
$errArray[] = $fieldName. ' is required';
}else{
// If the input is less than min or more than max -
//compose the error and add it to the errors array.
if(strlen($input) < $min || strlen($input) > $max ){
$errArray[] = 'Please enter your ' .$fieldName.' between ' .$min. ' and ' .$max. ' letters.<br>';
}
// Checking against the given pattern.the array.
if(!preg_match($patterns, $input)){
//if the given example is not empty, add it to the error message.
$example = ($example) ? ', (Example: ' .$example. ')' : '';
$errArray[] = 'Wrong format of ' .$fieldName . $example;
}
}
}
When you try to check a variablen input, says $foo:
$foo = $_POST['foo'];
validateFormInput($foo, 'Foo name', 'yes', 5, 20, '/^[a-zA-Z]$/');
So for the above, the parameters are:
$foo = $input , the input value.
$fieldName = Foo Name , the input name in the error message.
$isRequired = yes, checks whether it is required or not.
$min = 5 , the min allowed characters.
$max = 20 , max allowed characters
$pattern = '/^[a-zA-Z]$/' , the pattern to check against.
$example = '' , I didn't provide an example, but here it could be (Example: CA) or (###)###-### format.
Finally we check if the $errArray is empty, then no erros found, else we loop through the errors array and echo out all caught errors.

Categories