Codeigniter insert array into database - php

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

Related

Why does the validation for my codeigniter website fail everytime?

I have a controller code like so:
$validation=service('validation');
$validation->reset();
$data = [
'validation' => $validation,
];
if ($this->request->getMethod() === 'post'){
$validation->setRules( [ 'comment' => 'required',] );
if($validation->run()) {
$CommentsModel->save(['Comment' => $this->request->getPost('comment'),]);
return redirect()->to('/someplace...');
}
}
}
return view('templates/header', $data)
. view('templates/menu')
. view('addComment', $data)
. view('templates/footer');
}
Everytime my form is posted, the validation fails... even when I have something in comment! Any idea why this would be?
This is the form:
<form action="/Add/<?= esc($book)?>/<?= esc($chapter) ?>" method="post">
<?= csrf_field() ?>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" ><?= set_value("comment")?></textarea><br />
<?php if($validation->hasError('comment')) echo '<p class="validationError">' . $validation->getError('comment') . '</p>'?>
<input type="submit" name="submit" value="Add Comment" />
</form>

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";
}
}

Codeigniter error inserting array in db

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);

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.

php validation not working

I am developing a simple registration form that validates with php. problem is rather than the validation echoing on screen once I click the submit button nothing happens, no error or brake it dose not show me what the error is, I believe my logic is correct but I believe there may be a mistake.
would appriciate any advise or identification of my problem
register.php
<?php
require_once 'core/init.php';
if(Input::exists()) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
),
));
if($validation->passed()) {
echo 'Passed';
} else {
print_r($validation->errors());
}
}
?>
<form action="" methord="post">
<div class="field">
<lable for="username">Username</lable>
<input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
</div>
<div class="field">
<lable for="password">Choose Your Password</lable>
<input type="password" name="password" id="password">
</div>
<div class="field">
<lable for="password_again">Verify Password</lable>
<input type="password" name="password_again" id="password_again">
</div>
<div class="field">
<lable for="name">Your Name</lable>
<input type="text" name="name" value="<?php echo escape (Input::get('name')); ?>" id="name">
</div>
<input type="submit" value="Register">
</form>
Validation.php
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __contruct() {
$this->_db = DB::getInstance();
}
public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = $source[$item];
if($rule == 'required' && empty($value)) {
$this->addError("{$item} is required")
} else {
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError() {
$this->_errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
UPDATE
Have corrected typo that was correctly pointed out by #PeteR, but there is still a problem that the echo validation is not printing out.
Link to form
http://stuweb.cms.gre.ac.uk/~ob219/membership/register.php
Looks like you have a typo, fella.
if($rule == 'requierd' && empty($value)) {
You also have a semicolon missing here:
$this->addError("{$item} is required");
----^
And another typo:
<form action="" methord="post">
Should be method...
And finally, try this:
private function addError($error) {
Input::exists()
returns false/null or contains errors, thus, the if statement is not true
if(Input::exists()) {
and the code inside of it (validation) does never get executed.
Debug with
print_r(Input::exists());
You should also change your if to a real condition:
if(Input::exists() === true) {
Enable error reporting in PHP (from http://blog.flowl.info/2013/enable-display-php-errors/)
<?php
// Put these lines to the top of your script
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
ini_set('xmlrpc_errors', true);
Update - Yet another one:
private function addError() {
$this->_errors[] = $error;
}
Method has no parameters..
private function addError($error) {
$this->_errors[] = $error;
}

Categories