首先,我仍然是PHP的新手,所以请原谅我缺乏理解。我正在处理一个表单,该表单从多个选项中获取选项,并根据这些选项提供用户结果。此表单还存储这些搜索查询,以便以后可以导出它们。
最初,表单只有四个参数需要存储,但现在我添加了第五个,这使得事情不那么合作。我已经搜索过,尝试过多种不同的东西,但是我已经碰壁了,正在寻求帮助。
用户选择一个或全部可用选项的目的是什么。前四个选项是简单的是/否问题,值为1表示是,0表示否。第五个是一系列县名,其值在数据库中设置为其ID。县选择选项通过Smarty动态填充。
这是用于存储这些值的PHP。
public function recordFilter($args)
{
$db = DBManager::getConnection();
$_POST['type'] = 'f'; // type of search, find providers
foreach($args as $key => $a)
{
if(isset($_GET['county']) && is_numeric($_GET['county'])
{
$_POST[$key] = $a ? (int)$_GET['county'] : 0; // store value of last parameter, or 0 if not set
}
$_POST[$key] = $a ? "y" : "n"; // store 'y' if $a is set, 'n' if not
var_dump($_POST[$key]);
}
parent::save();
}
目前正在发生的事情是我能够将所有值都放入此函数中,并迭代它们。但是因为我已经介绍了第五个字段(并且通过我尝试将它们拼凑在一起的不同方法)要么我的第五个参数设置为'y',它不会存储在数据库中,因为它的字段是一个int (2),或者前四个参数的设定值取第五个参数的值,并在其字段中结束与该县相关联的id。
我想要学习的是有什么更好的方法来处理这类问题?我想也许一个while循环适合迭代前四个参数并在完成后处理第五个参数,但是找出它的语法有点超出我的意思。我也尝试过一个switch语句,但这根本不起作用。 if语句似乎是这种情况下的大扳手,因为如果设置'county',它会抛出整个循环。任何帮助将不胜感激。
答案 0 :(得分:0)
由于编写代码在评论上看不正确,我在这里发布我的猜测。如果您描述了更多代码,例如$args
是什么,或者您处理请求的方式,那么它将帮助人们了解您的问题。
由于这是$_GET
请求,因此您无法使用$_POST
foreach ($args as $key => $a) {
$_POST[$key] = $a ? "y" : "n"; // store 'y' if $a is set, 'n' if not
}
if (isset($_GET['county']) && is_numeric($_GET['county']) {
$_POST['county'] = $a ? (int)$_GET['county'] : 0; // store value of last parameter, or 0 if not set
}
第二,我认为这是更好的方法
将它们分配给另一个变量,不要忘记重构parent::save()
方法
public function recordFilter($args)
{
$db = DBManager::getConnection();
$request = [];
foreach ($args as $key => $a) {
//Sounds like you forgot to check if the $_POST[$key] is set
$request[$key] = isset($_POST[$key], $a) ? "y" : "n";
}
//You don't have to assign a value to super global $_POST with key of type
$request['type'] = 'f';
//Or you may need if statement if this field doesn't a required field
$request['county'] = (int) $_GET['county'];
parent::save($request);
}
在你父类的某个地方
protected function save(array $request)
{
//this is your bussiness
}
因为我只是猜测$args
是什么,所以这比更好的更好
filter_input()
和filter_input_array()
public function recordFilter($args)
{
$db = DBManager::getConnection();
//This array will be used for validating the input $_POST.
//First, I grab the key of $args then assign the value
//to $validate with the same key to return it as bool
$validate = [];
foreach(array_keys($args) as $key) {
$validate[$key] = FILTER_VALIDATE_BOOLEAN;
}
//Get the post request value
$request = filter_input_array(INPUT_POST, $validate);
//You don't have to assign a value to super global $_POST with key of type
$request['type'] = 'f';
//Receive 'county' only if it's int and greater than 1 and lower than 99
$options = ['options' => ['min_range' => 1, 'max_range' => 99]];
$request['county'] = filter_input(INPUT_GET, 'county', FILTER_VALIDATE_INT, $options);
parent::save($request);
}
同样,parent::save()
方法需要重构。