2012-05-10 18:20



I have a form with over 100 dynamically named fields, that post to a php file, I want to take all the fields that are posted to the php file which is currently:

Array ( [option_page] => plugin_options 
[action] => update 
[_wpnonce] => a51bfc281a 
[_wp_http_referer] =>/wp-admin/options-general.php page=plug.php 
[13939069] => 
[2171] => 
[3600645] =>
[2168] => 
[13937024] => 
[submit] => Save Changes 
[__qca] => P0-1887521465-1334258158937 
[s_vi] => )

From this I want to insert the data into a mysql table in the format:

id      | option_name     | value
autonum | post data key   | post data value

But the issue is I am only intrested in the post data value after: [_wp_http_referer] but before [submit] so these can be used as reference points.

The part I am stuggling with is:

  • how would I get only that part of the post data dynamically?
  • How would I get the required array keys and insert it into the table dynamically?

Many thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanguanye4124 duanguanye4124 9年前

    You mat try this

    $start = array_search("_wp_http_referer",array_keys($_POST))+1;
    $end = array_search("submit",array_keys($_POST))-1;
    $newArr=array_slice($_POST, $start, $end);
    foreach($newArr as $k=>$v)
        // $k is the key name and $v is the value of that key
        //echo $k."=".$v."<br />";  
        $sql="INSERT INTO table_name VALUES (null, ".$k.", ".$val.")";
    点赞 评论 复制链接分享
  • douzhangcuo2174 douzhangcuo2174 9年前

    You could do something like this:

    $discard_array = array('option_page', 'action', '_wpnonce', '_wp_http_referer', 'submit', '__qca', 's_vi');
    $good_array = array();
    foreach ($_POST as $key => $val)
        if (!in_array($key, $discard_array)) $good_array[$key] = $val;
    // use $good_array to insert your data into db

    Or, if all of the "good" values have always numeric keys, here's a simplified variation:

    $good_array = array();
    foreach ($_POST as $key => $val)
        if (is_numeric($key)) $good_array[$key] = $val;

    Hope that helps.

    点赞 评论 复制链接分享
  • drhe80011 drhe80011 9年前

    The keys you want seem to be all numeric, so you could only store those. Like others before me, I also suggest using PDO for added security and convenience.

    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
    foreach($_POST as $key => $value) {
        if(preg_match("/^[0-9]+$/", $key) {
            $stmt = $dbh->prepare('INSERT INTO table_name(option_name, value) VALUES (?, ?)');
            $stmt->execute(array($key, $value));
    点赞 评论 复制链接分享
  • dsd119120 dsd119120 9年前
    $counter = 0;
    foreach($_POST as $key=>$value)
    if($key == "_wp_http_referer")
    $counter = 1;
    if($counter == "1")
    if($key != "submit")
    mysql_query("INSERT INTO table_name(id, option_name, value) VALUES ('','".mysql_real_escape_string($key)."','".mysql_real_escape_string($value)."')");
    点赞 评论 复制链接分享