簡體   English   中英

在數據庫中存儲會話數組

[英]Store Session Array in Database

我有陣列會議....

$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);

我想將它們存儲在我的數據庫中......

$que = "Insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$_SESSION['Names'][0], $_SESSION['Location'][0])','$_SESSION['Names'][1], $_SESSION['Location'][1])','$_SESSION['Names'][2], $_SESSION['Location'][2])')";
$exec = mysql_query($que);

保存后,我的數據庫(tblpeople)顯示以下值:

DateTimePosted: 2014-01-03 16:23:02

first: Array [0],Array [0]

第二: 數組[1],數組[1]

第三: 數組[2],數組[2]

相反,我希望我的輸出是......

DateTimePosted: 2014-01-03 16:23:02

第一名: 11,35

第二名: 15,42

第三名: 26,10

怎么了?

要在字符串中展開多維數組,需要將它們用大括號括起來:

$que = "Insert into tblpeople (DateTimePosted, first, second, third)
        VALUES(now(),
               '{$_SESSION['Names'][0]}, {$_SESSION['Location'][0]}',
               '{$_SESSION['Names'][1]}, {$_SESSION['Location'][1]}',
               '{$_SESSION['Names'][2]}, {$_SESSION['Location'][2]}')";

您還在值中添加了一些括號。

但是,這似乎是將數據存儲到數據庫中的一種非常奇怪的方式。 為什么每列中有兩個以逗號分隔的值,而不是將每個值拆分為單獨的列? 為什么要將數組元素存儲到不同的列中,而不是將每個值與單獨的表一起使用?

使用此功能

$x=serialize($_SESSION['Names']);

它返回一個字符串,你可以保存在任何地方

而這個功能扭轉了它

$_SESSION['Names']=unserialize($x);

嘗試這個

<?php
session_start();
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);


$refNumbers = $_SESSION['Names'];
$partIds = $_SESSION['Location'];



$combined = array();

foreach($refNumbers as $index => $refNumber) {
    if(!array_key_exists($index, $partIds)) {
        throw OutOfBoundsException();
    }

    $combined[] = array(
        'Names'  => $refNumber,
        'Location' => $partIds[$index]
    );
}

print_r($combined);

$combine1 = implode(",",$combined[0]);
$combine2 = implode(",",$combined[1]);
$combine3 = implode(",",$combined[2]);



$que = "insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$combine1','$combine2','$combine3')";
//$exec = mysql_query($que);

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM