我将多个表单输入值存储为MySql中的序列化数据:
if(isset($_POST['bts'])):
$id = "175";
if(isset($_POST['bts'])){
$stmt = $mysqli->prepare("UPDATE personal SET invoice=? WHERE id_personal=?");
$stmt->bind_param('ss', serialize($_POST), $id);
if($stmt->execute()):
HTML:
<form role="form" method="post" id="form">
<input type="text" class="form-control" name="nazov[]" id="nazov">
<input type="text" class="form-control" name="cena[]" id="nazov">
<button id="save"class="btn btn-success btn-lg" name="bts">Save</button>
<button id="saveprint" class="btn btn-success btn-lg" name="bts"><span class="glyphicon glyphicon-print" aria-hidden="true"></span>Save and print</button>
</form>
使用jQuery我动态添加输入,因此有3个额外的输入行示例 序列化数据:
a:3:{s:5:"nazov";a:3:{i:0;s:3:"123";i:1;s:3:"789";i:2;s:3:"abc";}s:4:"cena";a:3:{i:0;s:3:"456";i:1;s:6:"101112";i:2;s:3:"def";}s:3:"bts";s:0:"";}
或
Array
(
[nazov] => Array
(
[0] => 123
[1] => 789
[2] => abc
)
[cena] => Array
(
[0] => 456
[1] => 101112
[2] => def
)
[bts] =>
)
我的问题是:在foreach函数中检索(反序列化和获取)此数据的最佳方法是什么?
$res = $mysqli->query("SELECT invoice FROM personal WHERE id_personal='175'");
$row = mysqli_fetch_assoc($res);
$unsRow = unserialize($row['invoice']);
foreach ($unsRow as $value) {
echo $value['nazov'];
}
Undefined index: nazov
期望的结果是:
Nazov:123 Cena:456
Nazov:789 Cena:101112
Nazov:abc Cena:def
答案 0 :(得分:1)
使用当前的json字符串,您可以获得配对值,如:
$res = $mysqli->query("SELECT invoice FROM personal WHERE id_personal='175'");
$row = mysqli_fetch_assoc($res);
$unsRow = unserialize($row['invoice']);
// check if you have `nazov`key and `cena` key, cause you need price too
if ($unsRow['nazov'] && $unsRow['cena']) {
foreach ($unsRow['nazov'] as $k => $v) {
if (!empty($unsRow['cena'][$k])) {
echo 'Nazov: ' . $v . ', cena: ' . $unsRow['cena'][$k];
}else
echo 'Nazov: ' . $v . ', cena: ' . "";
}
}
答案 1 :(得分:0)
这不是一个特别有用的存储机制,但这可行。
$unsRow = unserialize($row['invoice']);
for ( $i=0; $i<count($unsRow ); $i++) {
echo sprintf( "Nazov:%d Cena:%d\n",
$unsRow ['nazov'][$i],
$unsRow ['cena'][$i]
);
}