0

I am using a $_COOKIE[array] in order to save data for a single input. This input will only submit if the user entered the same value twice. For instance, if they submitted apple, then orange, then banana, then apple, the form would submit on the second appearance of "apple".

I read [this tutorial]( http://phpprogramming.wordpress.com/2007/03/06/php-cookies-tutorial-and-examples/).

for ($i = 1; $i < 10; $i++) {
    if (!isset($_COOKIE[$i])) {
        setcookie("query" . [$i],$query,time()+604800,"/");
        break1;
    }
}
foreach ($_COOKIE["query"] as $key => $value) {
    echo "$key:$value";
}

I believe it might be a syntax error since I get:

Warning: Invalid argument supplied for foreach()

If you know a better way (can't be mySQL), then please let me know!

user229044
  • 232,980
  • 40
  • 330
  • 338

2 Answers2

2

$_COOKIE["query"] is not an array, that's whats producing the error.

Bono
  • 4,757
  • 6
  • 48
  • 77
1

$_COOKIE['query'] can not store an array. This is also why you get an error when you try to use it in the foreach. You could serialize your array before saving it though. Something like this

$array = array();
for ($i = 1; $i < 10; $i++) {
    $array[] = $i;
}
setcookie("query",urlencode(serialize($array)),time()+604800,"/");

$query = unserialize(urldecode($_COOKIE['query']));
foreach ($query as $key => $value) {
    echo "$key:$value";
}

also have a look at this post update cookie value in php for the expalanation why the urlencode / urldecode is used

Community
  • 1
  • 1
Pevara
  • 14,242
  • 1
  • 34
  • 47
  • I'm getting Notice: unserialize(): Error at offset 0 of 8 bytes in C:\xampp\htdocs\search.php on line 83 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\search.php on line 84 –  Aug 07 '12 at 21:26
  • did not test my code, sorry. Found the solution here. http://stackoverflow.com/questions/7425774/update-cookie-value-in-php Will adjust my answer. – Pevara Aug 07 '12 at 21:34
  • After fiddling for an hour, I see you have to enter all the cookie values into $array = array(); I have not been able to figure out how to do this. –  Aug 07 '12 at 23:28