[英]PHP form validate using foreach and store value if and only there is no error
如果没有验证,我将拥有for字段数组并将数据保存到数据库中而不会出现问题。
我遇到的麻烦是在使用update_setting( $optionname, $optionvalue );
保存任何单个字段数据之前,先检查foreach迭代中是否存在错误update_setting( $optionname, $optionvalue );
当前代码正在保存除错误一以外的所有字段的数据。 因此,有什么方法可以首先验证所有字段,然后仅在没有单个错误的情况下才存储到数据库。 否则,请在页面上拍摄错误消息。
$errors = [];
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
// check the field if not set
if ( get_post_field( 'test' ) == '' ) {
$errors['test'] = 'Test field is required';
}
/**
* all loop items only should be add/update if there is not single error
* If any single error occure than it shold not save any single field data
*/
// add/update settings
elseif ( empty( $errors ) ) {
update_setting( $optionname, $optionvalue );
}
}
琐碎,但可能会起作用:)
$errors = [];
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
// check the field if not set
if ( get_post_field( 'test' ) == '' ) {
$errors['test'] = 'Test field is required';
}
/**
* loop all variables
*/
}
if ( count( $errors ) == 0) {
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
update_setting( $optionname, $optionvalue );
}
} else {
//routine or whatever you want to fire errors on the page
}
而不是每次迭代都用UPDATE查询命中数据库,为什么不只运行一个查询呢? 无论如何,如果将代码分成两个foreach循环,则可以实现目标:
// first loop validates each option
$errors = [];
foreach($optionNames as $optionName){
$optionValue = get_post_field($optionName);
if( strlen(trim($optionValue)) == 0 ){
$errors[] = sprintf("%s field is required!", $optionName);
// you could break here if you do not want to accumulate error messages
}
}
// if any errors were found, halt execution and output error messages
if( count($errors) > 0){
$errorMessages = implode(",", $errors);
die("Cannot save due to the following errors: " . $errorMessages);
}
// this will only execute if no errors were found
foreach($optionNames as $optionName){
$optionValue = get_post_field($optionName);
update_setting( $optionName, $optionValue );
}
这不是我要做的事情,但是我选择使用提供的代码回答您的问题,而不是提供完全不同的东西。
在可以选择提早返回(或在我的示例中,暂停执行)的情况下,尽量避免使用“ else”。 它通过提供通往所需结果的清晰路径来帮助清理代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.