PHP - Create cookie with multiple values

0

Good afternoon,

I am creating a script that will add cookies to the user account. The problem is ... I want to add multiple cookies for example:

If the user clicks add on ad 1 he will create a cookie with ID 1.   In 2 hours, if the user clicks the ad 10 he will add 1 more cookie, thus getting 2 cookies. A of ID 1 and of ID 10.

I created this like this:

    if(isset($_GET['add_favorite'])) {

       $favorite_id = mysqli_real_escape_string($con, sanitize($_GET['add_favorite']));
       setcookie("fav_ads_ids", $favorite_id, time() + (86400 * 30), "/");           
    } 

The problem is that it simply does an UPDATE to cookie, and that's not what I want. I want to create multiple cookies for multiple ads with the same name "fav_ads_ids".

    
asked by anonymous 05.10.2018 / 15:29

1 answer

2

Multipole cookies with the same index

json_encode() does the transformation of the php array to string, so it can be saved in cookie which has a string as its requirement

json_decode() transforms the array into string into the php format

if(isset($_GET['add_favorite'])) {
if(isset($_COKKIE['fav_ads_ids'])){ // verifica se o cokkie exite
    $ads = implode(',', json_decode($_COOKIE['fav_ads_ids'])); // organiza o array existente em: 1,2,3 
    $favorite_id = SELECT id FROM suaTabela WHERE id NOT IN ({$ads}) ORDER BY RAND() LIMIT 1 // faz a busca no sql de forma que remove os valores contidos na variavel $ads e ordana o resultado dinamico, selecionando apenas um para exibir
    $arr = json_decode($_COOKIE['fav_ads_ids']); // busca os valores do cokkie
}else{
    $favorite_id = SELECT id FROM suaTabela ORDER BY RAND() LIMIT 1 // seleciona todos os campos do sql e ordana o resultado dinamico, selecionando apenas um para exibir
    $arr = []; // novo valor do cokkie
}
$arr[] = $favorite_id['id']; //adiciona o novo item no array
$arr = json_encode($arr); // prepara o array para ser salvo
setcookie("fav_ads_ids", $arr, time() + (86400 * 30), "/"); // salva o array
}
print_r($_COOKIE['fav_ads_ids']); // imprime os valores do array

example

    
05.10.2018 / 15:57