Mysql
 sql >> Base de données >  >> RDS >> Mysql

Requête de mise à jour dynamique PHP PDO vers MYSQL

Ci-dessous se trouve la solution, où une entrée est vide, elle utilisera les données existantes dans ce champ et acceptera non seulement $_POST variables, mais toutes les variables.

// the list of allowed field names
$allowed = ["profile_picture","first_name","last_name", "phone_number", "nationality", "years_experience", "data" ];

// initialize an array with values:
$params = [];

// initialize a string with `fieldname` = :placeholder pairs
$setStr = "";

// loop over source data array
foreach ($allowed as $key)
{
    if (!empty([$key]) || $key != "" || $key != NULL)
    {

        if($GLOBALS[$key] != NULL){

        $setStr .= "`$key` = :$key ,";
        $params[$key] = $GLOBALS[$key];

        }else{

        $setStr .= "`$key` = $key ,";

        }

    }else{



    }
}
$setStr = rtrim($setStr, ",");

$params['id'] = $_SESSION['user_id'];

$dbh->prepare("UPDATE 001_user_table_as SET $setStr WHERE id = :id")->execute($params);