我对一些未定义的索引有一些问题。我意识到可以通过使用error_reporting(E_ALL);
, 或更改错误报告ini_set('display_errors', '1');
来解决此问题,但希望无需更改即可解决此问题。这是我抛出错误的代码块。
// print out errors
if (!empty($errors)){
echo '<div class="form_errors">';
foreach ($errors as $key => $value) {
var_dump($value);
if (isset($value) == null or empty($value)){
$value = ' A blank value ';
}
echo '<p>Please check '. $key . ' for errors.' . $value . 'is not a valid entry.</p>';
}
echo '</div>';
}
在提交时处理我的表单的部分是
if(isset($_POST['Submit'])){
//create the fields you would want required and what fields on form to check.
$fields = array(
'required' => array(
'name' => '^[a-zA-Z\`\-\s]{1,30}$', //only letters plus apostrophe and hyphens, and up to 30 characters
'Address1' => '^[a-zA-Z0-9\s\.]{1,50}$' // only letters plus numbers, spaces, periods, and up to 30 characters
),
'fields' => array(
'name' => $_POST['name'],
'Address1' => $_POST['Address1'],
'Address2' => $_POST['address2']
),
'redirect' => 'thankyou.php'
);
$errors = TForm::validate($fields);
// if no errors redirect
if (empty($errors)){
TForm::redirect($fields);
}
}
我的 TForm 类看起来像这样
class TForm {
//validation returns an error array when done.
public function validate($fields){
$errors = array();
foreach($fields['fields'] as $key=>$value) {
foreach ($fields['required'] as $req_key => $req_value) {
if ($key == $req_key){
$req_key = '\''.$req_value.'\'';
if (preg_match($req_key , $value) == false) {
$errors[$key] = $value;
}
}
}
}
return $errors;
}
//redirect function
public function redirect($fields){
header('Location: '. $fields['redirect']);
}
}
这也是我写过的第一堂课,所以如果有人愿意指出我本可以表现更好或打破标准的地方。~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~更新~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@jordan抱歉,我不清楚错误报告E_ALL
是我目前正在使用的,并且在生产机器上不会报告此错误,因为您将使用0
. 我的解决方案是使用!empty($_POST['Name']) ? $_POST['Name']:''
如果我的想法正确,如果它不为空,则使用其中的任何内容$_POST['Name']
,如果为空,则将值设置为''
.
'fields' => array(
'Name' => !empty($_POST['Name']) ? $_POST['Name']:'',
'Address1' => !empty($_POST['Address1']) ? $_POST['Address1']:'',
'Address2' => !empty($_POST['Address2']) ? $_POST['Address2']:''
)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~更新2~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@mike 使用 isset 导致该领域总是失败,即
'fields' => array(
'Name' => !isset($_POST['Name']) ? $_POST['Name']:'',
'Address1' => !isset($_POST['Address1']) ? $_POST['Address1']:'',
'Address2' => !isset($_POST['Address2']) ? $_POST['Address2']:''
)
当 name 等于有效变量时导致结果,例如 Frank Wiebenga
Please check Name for errors. A blank value is not a valid entry.
Please check Address1 for errors. A blank value is not a valid entry.
当 Name 等于有效变量时使用空方法,例如 Frank Wiebenga 正确返回
Please check Address1 for errors. A blank value is not a valid entry.