setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "DELETE FROM preferred WHERE user_id=:user_id"; $sth = $dbh->prepare($sql); $sth->execute(array(':user_id' => get_user_id())); $user_id = get_user_id(); foreach ($ids as $id) { $sql = "INSERT INTO preferred (user_id, brand_id) VALUES (:user_id, :brand_id)"; $sth = $dbh->prepare($sql); $sth->execute(array(':user_id' => $user_id, ':brand_id' => $id)); } } function get_preferred_brands() { global $host, $dbname, $user, $pass; $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # creating the statement $sql = "SELECT brand_id from preferred where user_id=:user_id"; $sth = $dbh->prepare($sql); $sth->setFetchMode(PDO::FETCH_OBJ); $sth->execute(array(':user_id' => get_user_id())); $brands = $sth->fetchAll(); foreach ($brands as $brand) { $ret[$brand->brand_id] = $brand->brand_id; } return $ret; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { try { save_preferred_brands ($_POST['ids']); header('location:view_preferred.php'); } catch (Exception $e) { echo $e->getMessage(); } } else { try { $brandService = new BrandService(); $brands = $brandService->getAllBrands(); $preferred = get_preferred_brands(); foreach ($brands as $brand) { if (isset($preferred[$brand->id])) { $brand->checked = true; } } $smarty = new Smarty; $smarty->assign('brands', $brands); $smarty->display('views/select_preferred.tpl'); } catch (Exception $e) { echo $e->getMessage(); } } ?>