Styling a variable data without undeclared variable error - php

I have an error and that is happening because I'm changing the $item name cause I want it to be uppercase. I've already done it for most of my code but for some reason I'm having some trouble doing so in here.
Here is the code:
public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = $source[$item];
$item = escape($item);
if ($rule === 'required' && empty($value)) {
$error = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($error) . " is required");
} else if(!empty($value)){
switch($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError(ucfirst($item) . " must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError(ucfirst($item) . " must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$item = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($item) . ' does not match ' . $rule_value);
}
break;
case 'unique':
$check = $this->_db->get('*', $rule_value, array($item, '=', $value));
if ($check->count()){
$this->addError(ucfirst($item) . ' is already in use!');
}
break;
}
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
Problematic code is:
if ($rule === 'required' && empty($value)) {
$item = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($item) . " is required");
}
I'm trying to make it so it outputs Password again is required instead of password_again is required. Everything in the switch($rule) statement is working properly but like I said I don't know why it doesn't work at that specific line. Anyone got an idea?
Exact Error: Notice: Undefined index: password confirm in C:\xampp\htdocs\classes\Validate.php on line 13.
What I thought of:
Suppression of the notice. This is good but I would really love it if this can be fixed.
Code Request [Source & Item]:
$validation = $validate->check($_POST, array(
'email' => array(
'required' => true,
'min' => 7,
'max' => 64,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 7,
'max' => 32
),
'password_confirm' => array(
'required' => true,
'matches' => 'password'
)
));
Var Dump Result:
string(5) "email"
Notice: Undefined property: Validate::$addError in C:\xampp\htdocs\classes\Validate.php on line 18
NULL string(8) "password"
Notice: Undefined property: Validate::$addError in C:\xampp\htdocs\classes\Validate.php on line 18
NULL string(16) "password confirm"
Notice: Undefined property: Validate::$addError in C:\xampp\htdocs\classes\Validate.php on line 18
NULL
Notice: Undefined index: password confirm in C:\xampp\htdocs\classes\Validate.php on line 13
New Working Code:
if ($rule === 'required' && empty($value)) {
$error = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($error) . " is required");
}

You're missing an empty check which is why the notice gets displayed when email, password or password_confirm is missing:
if( !empty( $source[$item] ) )
{
$value = $source[$item];
$item = escape($item);
if ($rule === 'required' && empty($value)) {
$item = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($item) . " is required");
} else if(!empty($value)){
switch($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError(ucfirst($item) . " must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError(ucfirst($item) . " must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$item = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($item) . ' does not match ' . $rule_value);
}
break;
case 'unique':
// $check = $this->_db->get('*', $rule_value, array($item, '=', $value));
if ( 1 == 1 ){
$this->addError(ucfirst($item) . ' is already in use!');
}
break;
}
}
}
else
{
$this->addError( $item . ' cannot be empty!' );
break;
}
I would recommend a simpler solution.
Full replication as requested:
function escape( $sValue )
{
return trim( $sValue );
}
class test
{
public $aErrors = array();
public function addError( $sError )
{
$this->aErrors[] = $sError;
}
public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
if( !empty( $source[$item] ) )
{
$value = $source[$item];
$item = escape($item);
if ($rule === 'required' && empty($value)) {
$item = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($item) . " is required");
} else if(!empty($value)){
switch($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError(ucfirst($item) . " must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError(ucfirst($item) . " must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$item = str_replace(array('_'), ' ', $item);
$this->addError(ucfirst($item) . ' does not match ' . $rule_value);
}
break;
case 'unique':
// $check = $this->_db->get('*', $rule_value, array($item, '=', $value));
if ( 1 == 1 ){
$this->addError(ucfirst($item) . ' is already in use!');
}
break;
}
}
}
else
{
$this->addError( $item . ' cannot be empty!' );
break;
}
}
}
}
}
$_POST[ 'email' ] = '';
$_POST[ 'password' ] = '';
$_POST[ 'password_confirm' ] = '';
$aValidation = $cTest->check( $_POST,
array( 'email' => array( 'required' => true, 'min' => 7, 'max' => 64, 'unique' => 'users' ),
'password' => array( 'required' => true, 'min' => 7, 'max' => 32 ),
'password_confirm' => array( 'required' => true, 'matches' => 'password' ) ));
var_dump( $cTest->aErrors );
var_dump( $aValidation );

Related

Change the Value field to percentage field in codeigniter OSPOS

This is add new gift page in OSPOS in CodeIGniter . there are four fields in that gifcard_id, person_id, giftcard_number, value I want Change the Value Field to Percentage of total price of the items that customer bought . the items are stored in another table. How can i do that ?
my model
/*
Gets gift card value
*/
public function get_giftcard_value($giftcard_number)
{
if( !$this->exists($this->get_giftcard_id($giftcard_number)) )
{
return 0;
}
$this->db->from('giftcards');
$this->db->where('giftcard_number', $giftcard_number);
return $this->db->get()->row()->value;
}
/*
Updates gift card value
*/
public function update_giftcard_value($giftcard_number, $value)
{
$this->db->where('giftcard_number', $giftcard_number);
$this->db->update('giftcards', array('value' => $value));
}
My Controller
public function save($giftcard_id = -1)
{
$giftcard_number = $this->input->post('giftcard_number');
if($giftcard_id == -1 && trim($giftcard_number) == '')
{
$giftcard_number = $this->Giftcard->generate_unique_giftcard_name($this->input->post('value'));
}
$giftcard_data = array(
'record_time' => date('Y-m-d H:i:s'),
'giftcard_number' => $giftcard_number,
'value' => parse_decimals($this->input->post('value')),
'person_id' => $this->input->post('person_id') == '' ? NULL : $this->input->post('person_id')
);
if($this->Giftcard->save($giftcard_data, $giftcard_id))
{
$giftcard_data = $this->xss_clean($giftcard_data);
//New giftcard
if($giftcard_id == -1)
{
echo json_encode(array('success' => TRUE, 'message' => $this->lang->line('giftcards_successful_adding') . ' ' .
$giftcard_data['giftcard_number'], 'id' => $giftcard_data['giftcard_id']));
}
else //Existing giftcard
{
echo json_encode(array('success' => TRUE, 'message' => $this->lang->line('giftcards_successful_updating') . ' ' .
$giftcard_data['giftcard_number'], 'id' => $giftcard_id));
}
}
else //failure
{
$giftcard_data = $this->xss_clean($giftcard_data);
echo json_encode(array('success' => FALSE, 'message' => $this->lang->line('giftcards_error_adding_updating') . ' ' .
$giftcard_data['giftcard_number'], 'id' => -1));
}
}

Undefined index: sub

I have problem with upload field. Error page image
Actualy when I add upload field to form script gives an error.
The server gives an error for this line: $filenamefields[$group]['sub']
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
and this line: $this->files['size']['fields']);
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
file codes :
<?php
class Orders extends CActiveRecord
{
public $fields;
public $files;
public $file;
public $remove;
public function tableName()
{
return 'orders';
}
public function rules()
{
return array(
array(
'name, start_date, ordertype, user',
'required'
),
array(
'status, ordertype, user',
'numerical',
'integerOnly' => true
),
array(
'name',
'length',
'max' => 200
),
array(
'finish_date, desc',
'safe'
),
array(
'id, name, start_date, finish_date, status, ordertype, user, desc',
'safe',
'on' => 'search'
),
array(
'fields,files',
'safe'
),
array(
'fields',
'customrule_add',
'on' => 'add'
),
array(
'fields',
'customrule_edit',
'on' => 'edit'
),
array(
'file, remove',
'safe',
'on' => 'answer'
)
);
}
public function customrule_add($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$fields = $this->$attribute;
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
}
private function customrule_addrec($fields, $required, $title, $type, $gprefix, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) || !$this->files['name']['fields'][$group]['sub'][$sgroup][$key]) {
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($filenamefields[$group][$key]) || !$filenamefields[$group][$key]) {
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
return $min_req;
}
public function customrule_edit($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$groups = CHtml::listData(Ordergroup::model()->findAll(array(
'select' => 'id,name,orderform',
'condition' => 'orderform = \'' . $this->ordertype . '\''
)), 'id', 'name');
$fields = $this->$attribute;
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'value ' . $title[$key] . ' Can not be empty');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][' . $key . ']', 'value ' . $title[$key] . 'Can not be empty');
}
}
}
}
}
if (!$min_req)
$this->addError($attribute, 'Choose a group');
}
public function add()
{
$name = $this->name;
$exists = Orders::model()->exists('`name` = \'' . $name . '\'');
if ($exists) {
$count = Orders::model()->count('`name` regexp \'^' . $name . ' - [0-9]+$\'');
$this->name = $name . ' - ' . ($count + 2);
}
$status = $this->save();
$status = $this->addsub(
$this->fields,
$status,
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']
);
if (!$status) {
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
return true;
}
private function addsub($thisfields, $status, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
foreach ($thisfields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active'] && $status) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
if (isset($fieldlist['sub'])) {
$status = $this->addsub(
$fieldlist['sub'],
$status,
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']
);
if(!$status)
return false;
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
if (!empty($value)) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($filenamefields[$group][$key]) && !empty($filenamefields[$group][$key])) {
$file = new CUploadedFile($filenamefields[$group][$key], $filetmpnamefields[$group][$key], $filetypefields[$group][$key], $filesizefields[$group][$key], $fileerrorfields[$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format' . $file->extensionName . 'is not true');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
}
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
return true;
}
public function edit()
{
$status = true;
foreach ($this->fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if (!$gofo) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
}
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
$sgofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $sgroup
));
if (!$sgofo) {
$sgofo = new GroupOfOrder('insert');
$sgofo->group = $sgroup;
$sgofo->order = $this->id;
$sgofo->save();
}
foreach ($sfieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) && !empty($this->files['name']['fields'][$group]['sub'][$sgroup][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group]['sub'][$sgroup][$key], $this->files['tmp_name']['fields'][$group]['sub'][$sgroup][$key], $this->files['type']['fields'][$group]['sub'][$sgroup][$key], $this->files['size']['fields'][$group]['sub'][$sgroup][$key], $this->files['error']['fields'][$group]['sub'][$sgroup][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group][$key]) && !empty($this->files['name']['fields'][$group][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group][$key], $this->files['tmp_name']['fields'][$group][$key], $this->files['type']['fields'][$group][$key], $this->files['size']['fields'][$group][$key], $this->files['error']['fields'][$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
} else {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if ($gofo) {
$gofo->delete();
$ovs = Ordervalues::model()->findAll('order = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where ordergroup=' . $group . ')');
foreach ($ovs as $ov) {
if ($ov->field0->type == 2)
unlink(Yii::app()->getBasePath() . '/../files/' . $ov->id);
$ov->delete();
}
}
}
}
$status = ($status && $this->save());
return $status;
}
public function answer()
{
if ($this->remove) {
foreach ($this->remove as $id => $f) {
if ($f) {
$filemodel = Orderfiles::model()->findByAttributes(array(
'id' => $id,
'order_id' => $this->id
));
if ($filemodel) {
$filemodel->delete();
$path = Yii::app()->basePath . '/../files/answers/' . $id;
if (file_exists($path))
unlink($path);
}
}
}
}
$file = CUploadedFile::getInstance($this, 'file');
if ($file) {
$fm = new Orderfiles('insert');
$fm->name = $file->name;
$fm->size = $file->size;
$fm->order_id = $this->id;
if ($fm->save() && $this->save())
return $file->saveAs('files/answers/' . $fm->id);
return false;
}
return $this->save();
}
public function fill_in_fields()
{
$this->fields = array();
foreach ($this->ordervalues as $field) {
$f = $field->field0;
if (!isset($this->fields[$f->ordergroup]['active']))
$this->fields[$f->ordergroup]['active'] = true;
$this->fields[$f->ordergroup][$f->id] = $field->value;
}
}
public function getPrice()
{
return Yii::app()->db->createCommand('select sum(price) from ' . Ordergroup::model()->tableName() . ' where id in (select `group` from ' . GroupOfOrder::model()->tableName() . ' where `order` = ' . $this->id . ')')->queryScalar();
}
public function deleteTree()
{
$ovsff = Ordervalues::model()->findAll('`order` = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where type = 2)');
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/' . $value->id;
if (file_exists($path))
unlink($path);
}
}
Ordervalues::model()->deleteAll('`order` = ' . $this->id);
GroupOfOrder::model()->deleteAll('`order` = ' . $this->id);
$status = true;
$ovsff = Orderfiles::model()->findAll('`order_id` = ' . $this->id); // files of answered orders
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/answers/' . $value->id;
if (file_exists($path))
unlink($path);
$status = $status && $value->delete();
}
}
$trans = $this->trackCode;
$status = $this->delete();
$trans->delete();
return $status;
}
public function relations()
{
return array(
'orderfiles' => array(
self::HAS_MANY,
'Orderfiles',
'order_id'
),
'ordertype0' => array(
self::BELONGS_TO,
'Orderform',
'ordertype'
),
'trackCode' => array(
self::BELONGS_TO,
'Transaction',
'track_code'
),
'user0' => array(
self::BELONGS_TO,
'Users',
'user'
),
'ordervalues' => array(
self::HAS_MANY,
'Ordervalues',
'order'
),
'tickets' => array(
self::HAS_MANY,
'Ticket',
'order_id'
)
);
}
public function attributeLabels()
{
return array(
'id' => 'Code',
'name' => 'Name',
'start_date' => 'Date',
'finish_date' => 'End Date',
'status' => 'status',
'ordertype' => 'Type',
'user' => 'User',
'track_code' => 'Pay code',
'desc' => 'Description',
'file' => 'File'
);
}
public function getStatus()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
3 => 'Draft'
);
return $status[$this->status];
}
public function getButton()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
4 => 'Draft'
);
if ($this->status == 0) {
return CHtml::button('Pay', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('financial/invoice', array(
'id' => $this->track_code
)) . '\''
));
}
return CHtml::button('Details', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('service/order', array(
'id' => $this->id
)) . '\''
));
}
public function search()
{
$criteria = new CDbCriteria();
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->name, true);
$criteria->compare('start_date', $this->start_date, true);
$criteria->compare('finish_date', $this->finish_date, true);
$criteria->compare('status', $this->status);
$criteria->compare('ordertype', $this->ordertype);
$criteria->compare('user', $this->user);
$criteria->compare('track_code', $this->track_code);
$criteria->compare('desc', $this->desc, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria
));
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
}

PHP multidimensional array repetitive output

The following code cycles through an array of requirements for user submitted data (in this case from a registration form) and outputs repetitive error messages. How to stop the repetitive messages?
if(!empty($_POST)){
$validate = array(
'username' => array(
'required' => true,
'min' => 3,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_confirm' => array(
'required' => true,
'matches' => 'password'
)
);
foreach($validate as $item => $rules)
{
foreach($rules as $rule => $rule_value)
{
$value = $_POST[$item];
$item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);
if($rule === 'required' && empty($value))
{
$errors[] = "{$item} is required <br>";
}
}
if(!empty($errors))
{
foreach($errors as $error)
{
echo $error;
}
}
else
{
echo 'Registration Successful <br>';
}
}}
Output:
username is required
username is required
password is required
username is required
password is required
password_confirm is required
Your loops have gotten a bit mixed up.
foreach($validate as $item => $rules)
{
foreach($rules as $rule => $rule_value)
{
$value = $_POST[$item];
$item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);
if($rule === 'required' && empty($value))
{
$errors[] = "{$item} is required <br>";
}
}
}
// This piece that prints out the errors (if they are present) needs
// to be moved outside the loop that creates the error array.
if(!empty($errors))
{
foreach($errors as $error)
{
echo $error;
}
}
else
{
echo 'Registration Successful <br>';
}
Also, maybe you simplified this code for the purpose of asking the question, but if this is all there is to it, why not just print the error at the time you find it instead of appending it to an array of errors? That way you only have to loop once. You can just use a boolean to see if there were errors.
$has_errors = false;
foreach($validate as $item => $rules)
{
foreach($rules as $rule => $rule_value)
{
$value = $_POST[$item];
$item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);
if($rule === 'required' && empty($value))
{
$has_errors = true;
echo "{$item} is required <br>";
}
}
}
if (!$has_errors) echo 'Registration Successful <br>';

Getting array key value in nested arrays

I need to get an array value with the key name being "name" but I can’t seem to figure it out. I am displaying an error when a user doesn’t fill out a field and I want it to be more specific. In my case when I output an error the page says fname needs to be filled but in an array in my script that checks the required things in a form I listed a name and I want it to display First Name needs to be filled. My code is below.
<?php
require_once 'Assets/Scripts/Core/Init.php';
if(Input::exists()){
if(Token::check(Input::get('token'))){
$Validate = new Validate();
$Validation = $Validate->check($_POST, array(
'fname' => array(
'name' => 'First Name',
'required' => true,
'min' => '2',
'max' => '16',
'alpha' => true
),
'lname' => array(
'name' => 'Last Name',
'required' => true,
'min' => '2',
'max' => '16',
'alpha' => true
),
'email' => array(
'name' => 'E-Mail',
'required' => true,
'max' => '128',
'email' => true,
'unique' => 'users'
),
'password' => array(
'name' => 'Password',
'required' => true
),
'pn' => array(
'name' => 'Phone Number',
'required' => true,
'max' => '10',
'num' => true
),
'student_id' => array(
'name' => 'School ID',
'required' => true,
'max' => '10',
'num' => true
)
));
if($Validate->passed()){
$user = new User();
$salt = Hash::salt(32);
try {
$user->create('users', array(
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'fname' => Input::get('fname'),
'lname' => Input::get('lname'),
'phone' => Input::get('pn'),
'student_id' => Input::get('student_id'),
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d H:i:s'),
'usergroup' => 1
));
} catch(Exception $e) {
die($e->getMessage());
}
}
else {
echo print_r($Validate->errors());
}
}
}
My validation class:
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct(){
$this->_db = DB::getInstance();
}
public function check($data, $items = array()){
foreach($items as $item => $rules){
foreach($rules as $rule => $rule_value){
trim($value = $data[$item]);
$item = escape($item);
if($rule === 'required' && empty($value)){
$this->addError("{$item} is required");
}
else if(!empty($value)){
switch($rule){
case 'min':
if(strlen($value) < $rule_value){
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value){
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $data[$rule_value]){
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()){
$this->addError("{$item} already exists.");
}
break;
case 'email':
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->addError("{$item} is not a valid email.");
}
break;
case 'num':
if(!is_numeric($value)){
$this->addError("{$item} can only contain numbers.");
}
break;
case 'alpha':
if(!ctype_alpha($value))
{
$this->addError("{$item} can only contain letters.");
}
break;
}
}
}
}
if(empty($this->_errors)){
$this->_passed = true;
}
return $this;
}
private function addError($error){
$this->_errors[] = $error;
}
public function errors(){
return $this->_errors;
}
public function passed(){
return $this->_passed;
}
}
Input class:
<?php
class Input {
public static function exists($type = 'post'){
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_POST)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item){
if(isset($_POST[$item])){
return $_POST[$item];
}
elseif(isset($_GET[$item])){
return $_GET[$item];
}
else {
return '';
}
}
}
I need to be able to output the value that has the key 'name' in the fname array. In this case it should output First Name.
You need to move your "is required" section out of the rules loop so you can actually use it easily. Then you can also reference the "pretty" name easily.
Simply change your Validate::check function to:
public function check($data, $items = array()){
foreach($items as $item => $rules){
// check required earlier (moved to here)
if(isset($rules['required']) && $rules['required'] && empty($data[$item])) {
$this->addError($rules['name'] . " is required");
}
Please note that I changed it to use $rules['name'] instead of $item so you get the "pretty" name.
foreach($rules as $rule => $rule_value){
trim($value = $data[$item]);
$item = escape($item);
// removed the required check here
else if(!empty($value)){
switch($rule){
case 'min':
if(strlen($value) < $rule_value){
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value){
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $data[$rule_value]){
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()){
$this->addError("{$item} already exists.");
}
break;
case 'email':
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->addError("{$item} is not a valid email.");
}
break;
case 'num':
if(!is_numeric($value)){
$this->addError("{$item} can only contain numbers.");
}
break;
case 'alpha':
if(!ctype_alpha($value))
{
$this->addError("{$item} can only contain letters.");
}
break;
}
}
}
}
}
change $item to $rules['name']
public function check($data, $items = array()){
foreach($items as $item => $rules){
foreach($rules as $rule => $rule_value){
trim($value = $data[$item]);
$item = escape($item);
if($rule === 'required' && empty($value)){
$this->addError("{$rules['name']} is required");
}
else if(!empty($value)){
switch($rule){
case 'min':
if(strlen($value) < $rule_value){
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value){
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $data[$rule_value]){
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()){
$this->addError("{$item} already exists.");
}
break;
case 'email':
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->addError("{$item} is not a valid email.");
}
break;
case 'num':
if(!is_numeric($value)){
$this->addError("{$item} can only contain numbers.");
}
break;
case 'alpha':
if(!ctype_alpha($value))
{
$this->addError("{$item} can only contain letters.");
}
break;
}
}
}
}

Warning: Invalid argument supplied for foreach() despite everything looking fine

I have an array that's being passed to a foreach and even though I've used foreach's hundred's of times before, I can't figure out why this is giving me the error, Warning: Invalid argument supplied for foreach()
switch($searchby){
case 0: // Name
print_r($data);
foreach($data as $key => $i){
if($key % 2 == 0 && $i == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
break;
}
The print_r prints a normal array, for instance (an actual example):
Array
(
[0] => Username
[1] => 4567
[2] => Password
[3] => 4567
[4] => Name
[5] => 4567
[6] => Age
[7] => 4567
[8] => Country
[9] => 4567
[10] => Type
[11] => Register
)
---- Since apparently it works, here's the entire callstack with the stack marked with <------: ----
/// Main.js ///
$("form#Register").submit(function () {
event.preventDefault();
$.post("php/proc.php",{'Command':'registerUser','Data':$(this).serialize()},function (data) { // <---- Original call
console.log(data);
});
return false;
});
// proc.php //
echo json_encode($MainLib->registerUser($db, $data)); // <--------- #1
class MainLib
{
public function registerUser($db, $data){
$pword = $this->hashpword($db, $result1[0]['value'], $result2[0]['value'], 'Register'); // <---------------- #2
}
public function hashpword($db, $data){
$uname = $this->searchData(0,'Username',$data); // <----------- #3
$pword = $this->searchData(0,'Password',$data);
$type = $this->searchData(0,'Type',$data);
switch($type){
case 'Register':
$salt = uniqid(rand(0,99999999),TRUE);
$db->query("UPDATE `Users` SET `salt`='" . $salt . "' WHERE `Username`='" . $uname . "'");
echo "UPDATE `Users` SET `salt`='" . $salt . "' WHERE `Username`='" . $uname . "'";
break;
$result = $db->query("SELECT * FROM `Users` WHERE `Username`='" . $uname . "'");
while($row = $result->fetch_assoc()){
$salt = $row['salt'];
}
}
$salt = base_convert($salt, 26, 10);
$pword = base_convert($pword, 26, 10);
$new_pword = $pword * $salt;
$new_pword = base_convert($new_pword, 10, 17);
$pword = hash('sha512',$new_pword);
return $pword;
}
public function searchData($searchby, $searchfor, $data){
$success = FALSE;
switch($searchby){
case 0: // Name
print_r($data);
foreach($data as $key => $i){ // <--------- ERROR
if($key % 2 == 0 && $i == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
break;
case 1: // Value
foreach($data as $key => $i){
if($key % 2 == 0 && $data[$key+1] == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
break;
}
if($success) return $matches;
return FALSE;
}
}
this might not be the right answer, i just want to know if this will suppress the error:
switch($searchby){
case 0: // Name
if(is_array($data)) { //--> add this validation
print_r($data);
foreach($data as $key => $i){
if($key % 2 == 0 && $i == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
} else {
die('Invalid Array!');
}
break;
}
try to add is_array condition if it could still print the value of $data and able to continue your script.

Categories