将数据库行保存在cookie中,然后检索它们

时间:2016-07-10 16:04:40

标签: php cookies

我想使用PHP setcookie(),我遇到了问题。事实上,我想从数据库中获取一些行,然后首先将它们保存在cookie中然后检索它们。我认为我的数据库中有一个包含多行的表,例如4列。我怎样才能做到这一点。这是我目前的代码。任何想法,谢谢你



private static final ConcurrentMap<Integer, Reference<MyClass>> INSTANCES = createInstanceMap();

private static ConcurrentMap<Integer, Reference<MyClass>> createInstanceMap() {
    // The set of keys to eagerly initialize instances for
    final Stream<Integer> keys = IntStream.range(0, 1000).boxed();
    final Collector<Integer, ?, ConcurrentMap<Integer, Reference<MyClass>>> mapFactory = Collectors
            .toConcurrentMap(Function.identity(), key -> new SoftReference<>(new MyClass(key)));
    return keys.collect(mapFactory);
}
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

在你的情况下,mysqli_fetch_array()函数返回一个多维数组,这意味着你应该引用$ row变量,例如:

$row[0][0] // 1st row, 1st column
$row[2][4] // 3rd row, 5th column

您还可以将数据作为一个辅助数组获取,请查看http://php.net/manual/en/mysqli-result.fetch-array.php

答案 1 :(得分:0)

以下是一个例子:

scalatags.Text

请查看此内容以获取更多信息:setcookie

答案 2 :(得分:0)

如果你真的想要/需要在cookie中保存整行,你可以在一个字符串中打包数组$ row,例如JSON:

//modified example from @Satty
$cookie_name="cook";
setcookie($cookie_name, json_encode($row),2 * 24 * 60 * 60 * 1000), "/");

//to read the cookie:
if(isset($_COOKIE[$cookie_name]))
    $row_from_cookie = json_decode($_COOKIE[$cookie_name]);

如果有某种特性,您可以确定它不会出现在您的数据中,因此它可以用作分隔符(例如。&#34;;&#34;)您也可以使用implodeexplode将整个数组打包在一个字符串中。

但是如果某些列是任何可以包含任何字符的类型,我就不会这样做,因为总会有一个你在数据中没有预料到的字符(例如if。你只存储名称,你可能认为没有人在他的名字中有分号,但仍然有人在输入字段中输入分号。)

相关问题