我试图弄清楚如何获取数组$_POST['custom']
并将值插入到 mysql 数据库中的单独行中。
var_dump($_POST['custom'])
给出数组array(1) { [0]=> string(12) "item1, item2, " }
,
我尝试了 foreach 和 echo 来查看是否可以单独生成行,但我只是返回了整个数组:
$array = $_POST['custom'];
foreach ($array as $item)
{
echo $item,'-';
}
并且输出item1, item2, -
不是item1-item2
我想要做的是将每个项目与购买该项目的 user_id 一起插入一个单独的行 - 例如:
user_id | item
-----------------
user_1 | item1
user_1 | item2
我可以使用然后你的标准插入查询插入单行,json_encode($_POST['custom'])
即使格式有点奇怪,引号和 [] (我已经尝试过 implode 和 explode 它们不起作用 - 但我可以忍受目前)。那张桌子看起来像
user_id | item
-----------------
user_1 | ["item1,item2,"]
我的主要问题是如何获取值数组item1
,以用作单个值以将数据插入到每个项目的单行中item2
,etc
使其看起来像上面的第一个表。
编辑
html表单
<form name="paypalCheckout" action="<?php echo PPCART_URL; ?>" method="post">
<input type="HIDDEN" name="business" value="<?php echo PPCART_ACCOUNT; ?>">
<input type="HIDDEN" name="cmd" value="_cart">
<input type="HIDDEN" name="upload" value="1">
<input type="hidden" name="currency_code" value="<?php echo PPCART_CURRENCY; ?>">
<input type="hidden" name="lc" value="<?php echo PPCART_COUNTRY; ?>">
<input type="hidden" name="return" value="<?php echo PPCART_RETURN_URL; ?>">
<?php
if (isset ($_SESSION['paypalCart']))
{
foreach($_SESSION['paypalCart'] as $product)
{
$custom .= $product['name'].",";
}
}
?>
<input type="hidden" name="custom" value="<?php echo $custom?>">
//<input type="hidden" name="custom[]" value="<?php echo $custom?>"> I have also tried this
相关部分是$custom
变量 - 它已经初始化为$custom="";
解决方案
<?php
if (isset ($_SESSION['paypalCart']))
{
foreach($_SESSION['paypalCart'] as $product)
{
$custom .= $product['name'].",";
}
}
?>
<input type="hidden" name="custom" value="<?php echo $custom?>">
然后在处理 php 文件中我有
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$user_id = "Test";
$custom = $_POST['custom'];
//print_r($_POST['custom']); This is good to see what your array looks like before it gets trimmed
$trim = rtrim($custom, ",");
$explode = explode(',',$trim);
//print_r($_POST['custom']); Good way to check what it looks like after being trimmed to make sure you have trimmed it correctly.
foreach ($explode as $course_id)
{
$sql = $db->query("INSERT INTO `subscriptions`(`user_id`, `course_id`) VALUES ('".$user_id."','".$course_id."')");
if($sql)
{
echo "it's good";
}
else
echo "no good", mysql_error();
}