php POST form query update dinamic variable

前端 未结 1 1710
旧时难觅i
旧时难觅i 2021-01-26 11:54

i have this form

Name:
English:
1条回答
  •  深忆病人
    2021-01-26 12:29

    you just need to create a dynamic update array. Something like this:

    $languagesToUpdate = array();
    
    // this is an example, you should modify as your script:
    
    // create a variable/constant to make sure you update only allowed fields
    $allowedLanguages = array('english' => true, 'french' => true, 'spanish' => true, 'german' => true, 'other_language' => true);
    
    // iterate threw post and check for allowed languages and add to languagesToUpdate the language we need to update with it's value
    foreach ($_POST as $post => $value) {
        if (isset($allowedLanguages[$post]) && $allowedLanguages[$post]) {
            $languagesToUpdate[] = '`' . $post . '` = "' . utf8_encode($value) . '"';
        }
    }
    
    // add additional data like updated_on
    $languagesToUpdate[] = '`updated_on` = ' . time() . '';
    
    //update database
    $db = 'UPDATE `translations_structure` SET '.implode(', ', $languagesToUpdate).' WHERE `id` = '.(int)$id;
    
    // this will produce something like this:
    // UPDATE `translations_structure` SET `english` = "English text", `spanish` = "Spanish text", `updated_on` = 1479720637 WHERE `id` = 1
    

    0 讨论(0)
提交回复
热议问题