0

我一直在尝试编写一个函数,该函数将获取任何给定表单提交的 POST 值,将它们弹出到数组中,使用修剪循环遍历数组,addlashes 等将该值传递回一个变量,然后它可以是传递到数据库。

现在我遇到的障碍是在提交表单时将所有输入、文本区域、选择元素数据放入一个数组中。我遵循的代码

$fields = array($_POST['1'], $_POST['2']);

    $i = 0;
    foreach ($fields as $field) {
        $i++;
        ${'field'.$i } = trim(addslashes(strip_tags($field)));
        echo "POST field info #". $i ."&nbsp;-&nbsp;". ${'field'.$i }."<br />";
    }

正如您所看到的,这里一切都很好,尽管 POST 值名称仍在静态输入,我需要的是一种将 POST 数据输入循环的方法,该循环使用增量变量动态调用 POST 名称,然后弹出所有这些数据到同一个数组中。我尝试过的代码如下。

for ($ii=0;$ii++;) {
    foreach($_POST['$ii'] as $field) {
        $fields = array($field);
    }
}

    $i = 0;
    foreach ($fields as $field) {
        $i++;
        ${'field'.$i } = trim(addslashes(strip_tags($field)));
        echo "POST field info #". $i ."&nbsp;-&nbsp;". ${'field'.$i }."<br />";
    }

现在我知道这行不通,但我能感觉到我比较接近,所以我想知道是否有聪明的人可以帮助我整理最后一部分?很遗憾,我现在要睡觉了,至少 9 个小时都不会看这篇文章,抱歉。

提前致谢。

担。

4

2 回答 2

2
$arrayOfPostValues = $_POST;  // it already is an array
$arrayOfPostValues = array_map('strip_tags', $arrayOfPostValues);
$arrayOfPostValues = array_map('trim', $arrayOfPostValues);

或者,如果您真的非常想使用循环:

foreach ($arrayOfPostValues as &$value) {
   $value = trim(striptags($value));
}

我绝对建议不要使用addslashes,它的用途很小。改为使用mysql_real_escape_string准备好的语句

我还建议不要将数组中的值分解为单独的变量,它只会导致问题。如果你真的想这样做,这里有一个extract功能,它正是这样做的。但是,再次,不要这样做。数组是处理此类数据的完美方式。

于 2010-11-11T01:16:56.573 回答
0

You need to assign values to $_POST[1] and $_POST[2] to begin with, I've done this for you but normally they would be populated from a form I assume?

I'm not sure why you want to do this sort of thing: ${'field'.$key}, but I've left that part as is as I assume you must have a reason.

Anyway I've modified your code a bit, see below.

$_POST['1'] = '<h1>variable 1</h1>';
$_POST['2'] = '<h2>variable 2</h2>';

foreach($_POST as $key => $value){
    ${'field'.$key} = trim(addslashes(strip_tags($value)));
    echo "POST field info #". $key ." = ". ${'field'.$key}."<br />";
}

The above code outputs:
POST field info #1 = variable 1
POST field info #2 = variable 2

On a side note, using field names such as '1' and '2' is not very good. Try using something more descriptive but as I said above I assume you have a reason for doing this.


UPDATE: You can still get this to work for any form even if you are using specific names for the form elements. I have added a few lines below as an example for you.

$_POST['email'] = 'example@example.com';
$_POST['password'] = 'hgbks78db';
$_POST['name'] = '';

foreach($_POST as $key => $value){
    if($value==''){
        echo 'POST field "'.$key . '" is empty<br />';
        /* I added the name of the field that is empty to an error array 
        so you have a way of storing all blank fields */
        $a_error[] = $key;
    }
    else{
        echo 'POST field "'.$key . '" is not empty<br />';
    }
}
于 2010-11-11T01:56:23.060 回答