PHP将表单数据转换为多个MySQL条目

时间:2013-05-31 08:25:16

标签: php html mysql

大家好我正在尝试更改下面的代码,以表明如果客户在表单中选择多个产品,将为所选的每个产品创建不同的MySQL查询。

我非常确定每个循环都需要某种功能才能使其工作但不知道。

非常感谢任何帮助!

表格代码:

<input type="checkbox" name="TG01" value="TG01">China Travel Guide - $45.00<br/>
<input type="checkbox" name="TG01" value="TG02">Berlin Travel Guide - $45.00<br/>
<input type="checkbox" name="TG03" value="TG03">France Travel Guide - $45.00<br/>
<input type="checkbox" name="TG04" value="TG04">Thailand Travel Guide - $45.00<br/>

PHP代码:

<?php 
include("config.php");
$con=mysqli_connect("host","user","pass","somedb"); 
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$qtychina = $_POST["china_travel_guide"];
$qtyberlin = $_POST['berlin_travel_guide'];
$qtyfrance = $_POST['france_travel_guide'];
$qtythailand = $_POST['thailand_travel_guide'];

$china = $_POST["TG01"];
$berlin = $_POST['TG02'];
$france = $_POST['TG03'];
$thailand = $_POST['TG04'];

$sql="INSERT INTO ORDER_TBL (TRANSACTION_ID, CUSTOMER_ID, PRODUCT_ID, QUANTITY)
VALUES ('','$_SESSION[user]','$china','$qtychina')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));

exit;
}

echo "Congratulations your order has been processed!";

?>

3 个答案:

答案 0 :(得分:2)

将表单元素命名为TG[],PHP会将其解释为数组值,然后您可以像这样循环它们:

foreach ($_POST['TG'] as $country) {

    //$country will hold the value of the current checkbox.

}

答案 1 :(得分:0)

$data = array();
$data[0]['c'] = $_POST["china_travel_guide"];
$data[1]['c'] = $_POST['berlin_travel_guide'];
$data[2]['c'] = $_POST['france_travel_guide'];
$data[3]['c'] = $_POST['thailand_travel_guide'];

$data[0]['t'] = $_POST["TG01"];
$data[1]['t'] = $_POST['TG02'];
$data[2]['t'] = $_POST['TG03'];
$data[3]['t'] = $_POST['TG04'];
$i = 0;
while (count($data) < $i) {

    $sql="INSERT INTO ORDER_TBL (TRANSACTION_ID, CUSTOMER_ID, PRODUCT_ID, QUANTITY)
VALUES ('','$_SESSION[user]','$data[$i][c]','$data[$i][t]')"; 
$i++;              
}

答案 2 :(得分:0)

表格代码:

<input type="checkbox" name="TG[]" value="TG01">China Travel Guide - $45.00<br/>
<input type="checkbox" name="TG[]" value="TG02">Berlin Travel Guide - $45.00<br/>
<input type="checkbox" name="TG[]" value="TG03">France Travel Guide - $45.00<br/>
<input type="checkbox" name="TG[]" value="TG04">Thailand Travel Guide - $45.00<br/>

PHP代码:

if(!empty($_POST['TG'])){
 foreach($_POST['TG'] as $country){
    $sql="INSERT INTO ORDER_TBL (TRANSACTION_ID, CUSTOMER_ID, PRODUCT_ID, QUANTITY)
    VALUES ('','$_SESSION[user]','$country','$qty')";

    if (!mysqli_query($con,$sql))
     {
    die('Error: ' . mysqli_error($con));

    exit;
    }
 }
}