[英]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.