我想弄清楚如何採取數組$_POST['custom']
並將值插入MySQL數據庫中的單獨的行。我怎樣才能插入每個數組值作爲一個單獨的行在PHP和MYSQL
var_dump($_POST['custom'])
使得數組array(1) { [0]=> string(12) "item1, item2, " }
,
我試過的foreach和回聲,看看我是否可以單獨生產線,但我只是得到整個數組返回:
$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'])
,然後你的標準插入查詢,即使格式化有點奇怪用引號和[]插入單行(我都試過破滅和爆炸他們不這樣做工作 - 但我現在可以接受這一點)。這表看起來像
user_id | item
-----------------
user_1 | ["item1,item2,"]
我的主要問題是如何獲取值item1
,item2
,etc
被用作個人價值將數據插入到每件單排,使得它看起來像第一個數組上面的表格。
EDIT
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();
}
向我們展示您的html表單或看看「爆炸」 – worenga
您能否顯示print_r的輸出($ _ POST ['custom']) – Malkocoglu
@Malkocoglu print_r給我'Array([0] => item1, item2,)' – Fahad