首页 > 解决方案 > 解压 array_value() 的 $_POST 数组

问题描述

我有一些问题,我怀疑是由于误解了如何处理来自网络表单的 $_POST 数据。这让我绞尽脑汁,因为我的方法在一种情况下有效,但在它的继任者中却中断了。

简而言之:我可以在方法中调用 $_POST 的 key=>value 对,但我不能操作 $_POST 数组本身,它总是返回为 1。

初始情景。有关上下文和抱怨,请参阅评论。此方法有效:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $post = $_POST; // I'm aware $_POST is a superglobal and can be called within the method
    $cms->addPage($table, $post);
        
}

CMS 类的 addPage() 方法:

public function addPage($table, $post) {
    global $db; // SQL object declared in config

    $url = preg_replace('/\s+/', '-', $post['pageTitle']);

    $vals = array($post['pageTitle'], $post['isRoot'], $post['metaTitle'], $post['metaDesc'], $post['pageCont'], $url, $post['dateCreated'], $post['pageBanner']);

    $cols = array("pageTitle", "isRoot", "metaTitle", "metaDesc", "pageCont", "pageURL", "dateCreated", "pageBanner");

    $types = "sissssss";

    $db->prep_Insert($table, $cols);
    $db->bind_Prep($types, $vals); // This method unpacks the $vals array with ...
    $db->execute_Prep();
    $db->close_Prep();

    $_SESSION['success'] = 'Page Updated';
    header('Location: ' . DIRADMIN . 'manage/pages');
    exit();

}

这工作正常。直接在数据库中弹出,鲍勃是你的叔叔。但是,这个 CMS 应该能够处理多个表单对象,我不想为客户可能想要的每个自定义功能编写添加/更新方法。所以我想出了这个:

public function addContent($table, $post, $types) {
    global $db;
    $cols = self::getColumns($table); // Helper method I wrote to get column names from the table being added to
    array_shift($cols); // AUTO_INCREMENT is set in database, so knock off the ID row

    /* This is where it falls apart. All I want is to take the $_POST array 
       I got from the form and reduce it from associative to indexed. 
       The array_values() should do this, right? */
    $post = array_values($post);
    // $post = array_values($_POST); 
    /* Also doesn't work. It doesn't matter if I pass forward the 
       $_POST array as a parameter, or if I call it directly here. */

    /* Second attempt at getting $_POST into an indexed array. I don't need the keys. */
    /*$i = 0;
    $vals = array();
    foreach ($_POST as $key => $value) {
        $vals[$i] = $value;
        $i++;
    }*/

    $db->prep_Insert($table, $cols);
    $db->bind_Prep($types, $post); // This is where I got the initial unpacking error; can't unpack associative arrays. Okay, I'll use array_value($_POST). Except, that always just outputs 1, and breaks the prep statement anyway.

    $db->execute_Prep();
    $db->close_Prep();

    $_SESSION['success'] = 'Page Updated';
    header('Location: ' . DIRADMIN . 'manage/' . $table);
    exit();
}

所以重申一下,出于某种原因,我可以在初始方法中通过其单独的 key=>value 对获取 $_POST 数据,但是如果我尝试以任何方式操作 $_POST 数组(array_keys()、reset()、foreach 循环等),它将输出为 1。 print_r() 输出 1, var_dump() 输出空白,并且在异常消息中返回为 1。

处理我没有得到的 $_POST 数据是否有一些限制或规则?我不知道为什么我可以得到键值对,但是根本无法操作它。

标签: phparrayspost

解决方案


推荐阅读