PHP Snippet 1:
<?php
public static function postPreferences($selected_countries) {
$database = DatabaseFactory::getFactory()->getConnection();
// Get existing selections
$sqlExisting = 'SELECT country_selection FROM user_settings WHERE user_id = :user_id';
$queryExisting = $database->prepare($sqlExisting);
$queryExisting->execute([
':user_id' => Session::get('user_id')
]);
$existingSelections = null;
if ($queryExisting->rowCount() > 0) {
$existingSelections = $queryExisting->fetchRows(); // dont know this DatabaseFactory, just an example, expects an associative array
}
// Insert
if ($existingSelections === null && is_array($selected_countries) && count($selected_countries) > 0) {
$sqlInsert = 'INSERT INTO user_settings (user_id, country_selection)VALUES(:user_id, :country_selection)';
$queryInsert = $database->prepare($sqlInsert);
$queryInsert->execute([
':user_id' => Session::get('user_id'),
':country_selection' => implode(',', $country_selection)
]);
// Update
} else if (is_array($existingSelections) && count($existingSelections) === 1 && $existingSelections[0]['country_selection'] !== implode(',', $country_selection)) {
$sqlUpdate = 'UPDATE user_settings SET country_selection = :country_selection WHERE user_id = :user_id';
$queryUpdate = $database->prepare($sqlUpdate);
$queryUpdate->execute([
':user_id' => Session::get('user_id'),
':country_selection' => (count($country_selection) === 0 ? null : implode(',', $country_selection))
]);
}
return true;
}