在数据库中存储会话数组

时间:2014-01-06 06:05:54

标签: php mysql arrays

我有阵列会话......

$_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

第一个: 数组[0],数组[0]

第二名: 数组[1],数组[1]

第三: 数组[2],数组[2]

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

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

首先: 11,35

秒: 15,42

第三名: 26,10

怎么了?

3 个答案:

答案 0 :(得分:2)

要在字符串中展开多维数组,需要将它们用大括号括起来:

$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]}')";

您还在值中添加了一些括号。

但是,这似乎是将数据存储到数据库中的一种非常奇怪的方式。为什么每列中有两个以逗号分隔的值,而不是将每个值拆分为单独的列?为什么要将数组元素存储到不同的列中,而不是将每个值与单独的表一起使用?

答案 1 :(得分:0)

使用此功能

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

它会返回一个字符串,您可以将其保存在任何

的位置

并且此功能将其反转

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

答案 2 :(得分:0)

试试这个

<?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);

?>