我是php新手,有一个简单的问题,我正在开发一个插件,在元盒中我有一个将数据保存到数据库的函数,这是我用来保存的代码:
$models_to_insert = array();
for ($i = 1; $i <= 3; $i++) {
if (isset($_POST["car_model_$i"]) != "") {
$car_model = sanitize_text_field($_POST["car_model_$i"]);
}
if (isset($_POST["car_price_$i"]) != "") {
$car_price = sanitize_text_field($_POST["car_price_$i"]);
}
if (isset($_POST["car_brand_$i"]) != "") {
$car_brand = sanitize_text_field($_POST["car_brand_$i"]);
}
if (isset($_POST["car_year_$i"]) != "") {
$car_year = sanitize_text_field($_POST["car_year_$i"]);
}
if (isset($_POST["car_type_$i"]) != "") {
$car_type = sanitize_text_field($_POST["car_type_$i"]);
}
if (isset($_POST["car_basefee_$i"]) != "") {
$car_basefee = sanitize_text_field($_POST["car_basefee_$i"]);
}
if (isset($_POST["car_basemodel_$i"]) != "") {
$car_basemodel = sanitize_text_field($_POST["car_basemodel_$i"]);
}
if (isset($_POST["car_rcusa_$i"]) != "") {
$car_rcusa = sanitize_text_field($_POST["car_rcusa_$i"]);
}
if (isset($_POST["car_bono_$i"]) != "") {
$car_bono = 1;
} else {
$car_bono = 0;
}
$single_model = array(
\'post_id\' => $post_id,
\'car_model\' => $car_model,
\'car_price\' => $car_price,
\'car_brand\' => $car_brand,
\'car_year\' => $car_year,
\'car_type\' => $car_type,
\'car_basefee\' => $car_basefee,
\'car_basemodel\' => $car_basemodel,
\'car_rcusa\' => $car_rcusa,
\'car_bono\' => $car_bono
);
array_push($models_to_insert, $single_model);
}
if (cotizador_query_select($post_id) == null) {
foreach($models_to_insert as $model){
$wpdb->insert($table_name, $model);
}
} else {
$wpdb->delete($table_name, array(\'post_id\' => $post_id));
foreach($models_to_insert as $model){
$wpdb->insert($table_name, $model);
}
}
for计数一直到3,因为我有3倍于3款车型的输入:
但如果我只填充第一个模型,而将其他输入留空,则数据库中会有3条记录,其中有空字段,而不是只有一条记录,因为只填充了一个模型:
我怎么能忽略其余未填充的输入??