PHP mysql插入多条记录的Array数组获取问题
恳请好心大佬帮忙修正以下$Arr部分的代码购物车页面<!--这里是个while循环,购物车里面有多少种物品,每种物品的ID和数量是不固定也没有规律的--><div><in...
恳请好心大佬帮忙修正以下$Arr部分的代码
购物车页面
<!--这里是个while循环 ,购物车里面有多少种物品,每种物品的ID和数量是不固定也没有规律的-->
<div><input name="pid[]" value="10"><input name="amount[]" value="5"></div>
<div><input name="pid[]" value="13"><input name="amount[]" value="1"></div>
<div><input name="pid[]" value="14"><input name="amount[]" value="2"></div>
order.php 提交订单页面
<?php
$Arr = array($_POST['pid'],$_POST['amount']);
print_r($Arr);
/*现在打印出来的$Arr是这样的
Array (
[0] => Array (
[0] => 10
[1] => 13
[2] => 14
)
[1] => Array (
[0] => 5
[1] => 1
[2] => 2
)
)
*/
//导致下面的sql语句执行是insert into myorder (pid,amount) VALUES (10,13),(5,1);
/*******/
//上面要怎么修改才能变成下面这样的数组
//以及我想要的insert into myorder (pid,amount) VALUES (10,5),(13,1),(14,2);
/*
Array (
[0] => Array (
[0] => 10
[1] => 5
)
[1] => Array (
[0] => 13
[1] => 1
)
[2] => Array (
[0] => 14
[1] => 2
)
)*/
$sql = "insert into myorder (pid,amount VALUES ";
foreach ($Arr as $k => $v) {
$sql .= "(".$v[0].",".$v[1]."),";
}
$sql = substr($sql, 0,strlen($sql)-1);
mysql_query($sql,$conn);//$conn是数据库链接
?> 展开
购物车页面
<!--这里是个while循环 ,购物车里面有多少种物品,每种物品的ID和数量是不固定也没有规律的-->
<div><input name="pid[]" value="10"><input name="amount[]" value="5"></div>
<div><input name="pid[]" value="13"><input name="amount[]" value="1"></div>
<div><input name="pid[]" value="14"><input name="amount[]" value="2"></div>
order.php 提交订单页面
<?php
$Arr = array($_POST['pid'],$_POST['amount']);
print_r($Arr);
/*现在打印出来的$Arr是这样的
Array (
[0] => Array (
[0] => 10
[1] => 13
[2] => 14
)
[1] => Array (
[0] => 5
[1] => 1
[2] => 2
)
)
*/
//导致下面的sql语句执行是insert into myorder (pid,amount) VALUES (10,13),(5,1);
/*******/
//上面要怎么修改才能变成下面这样的数组
//以及我想要的insert into myorder (pid,amount) VALUES (10,5),(13,1),(14,2);
/*
Array (
[0] => Array (
[0] => 10
[1] => 5
)
[1] => Array (
[0] => 13
[1] => 1
)
[2] => Array (
[0] => 14
[1] => 2
)
)*/
$sql = "insert into myorder (pid,amount VALUES ";
foreach ($Arr as $k => $v) {
$sql .= "(".$v[0].",".$v[1]."),";
}
$sql = substr($sql, 0,strlen($sql)-1);
mysql_query($sql,$conn);//$conn是数据库链接
?> 展开
1个回答
2019-04-04
展开全部
<?php
$_POST['pid'] = array(
10,
13,
14,
);
$_POST['amount'] = array (
5,
1,
2,
);
$sql = "insert into myorder (pid,amount) VALUES";
foreach ($_POST['pid'] as $key => $pid) {
$amount = $_POST['amount'][$key];
$sql .= "({$pid}, {$amount}),";
}
$sql = trim($sql, ',');
echo $sql;
?>
试试这段代码,最后输出的sql就是:
insert into myorder (pid,amount) VALUES(10, 5),(13, 1),(14, 2)
追问
超级赞!感谢老铁!
追答
客气客气
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询