Wordpress插件如何将动态生成的表单字段数据插入数据库

Wordpress plugin how to insert data of form fields generated dynamically into database

我是 运行 一种将数据发布到数据库的表单,每个问题字段都有许多动态生成的选项,问题查询运行良好,但动态创建的选项(该查询运行到 500)不工作。

前端和html结构:

<input name="text" placeholder="Question text" type="text" id="text">
<input type="text" placeholder="text" name="option_text[]" class="fieldname">
<input type="number" placeholder="0" name="option_score[]" class="fieldtype">

jquery:运行正常

function abc(){

var fName = new Array();

jQuery('.fieldname').each(function(index, value){
       fName.push(jQuery(this).val());
})

var fType = new Array();

jQuery('.fieldtype').each(function(index, value){
       fType.push(jQuery(this).val());
})

jQuery.ajax({
        type: 'POST',
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: { action: 'savedataques', text: document.getElementById('text').value, textopt: fName, score: fType},              
        success: function(data){
            alert('success');
alert('data');
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
}

Php代码:数据查询正常,dataop查询运行时出现空白页错误

    function savedataques(){
    global $wpdb;
    
            $data = ($wpdb->insert('wp_dbquestions', array(
                        
                        'text'        => $_POST['text'],
                    )
            ));
    
 
 $lastid = $wpdb->insert_id;
            echo $lastid;

这就是问题所在:

$dataop = ($wpdb->insert('wp_questoptions', array(
                'question_id'        => $lastid
                'text'        => $_POST['textopt'],
                'score'        => $_POST['score'],
            )
    ));

        }
   
    exit;

die();
return true;
}
//
add_action('wp_ajax_savedataques', 'savedataques'); 
//add_action('wp_ajax_nopriv_savedataques', 'savedataques');

这是解决方案: 只需要在所有动态生成的选项上应用 foreach

    $i=0;
    $optiontext = $_POST['textopt'];
    foreach($optiontext as $key => $val ){

        $score = $_POST['score'][$i];
        $textopt = $_POST['textopt'][$i];
        $i++;

然后查询:

        $data = ($wpdb->insert('wp_questoptions', array(
                    'question_id' =>  $lastid,
                    'text'        => $textopt,
                    'score'        => $score,
                )
        ));

完成