多个SQL插入&表单验证在PHP中

时间:2011-12-03 06:01:00

标签: php mysql validation insertion

我正在尝试使用php和mysql对表单进行多个产品添加,我对这样做的概念感到困惑,

我期望的输出是,提供一个表格,其中至少有十行多个字段需要填写并在这些表格中进行验证,如果没有错误则继续插入。

到目前为止,这是我对单个表单插入的理解:

    $add_errors = array();

//if there is a post request
if ($_SERVER['REQUEST_METHOD'] == 'POST') { 

// do some validation
if (empty($_POST['name'])) {
        $add_errors['name'] = 'Please enter the name!';
}

if (empty($_POST['description'])) {
        $add_errors['description'] = 'Please enter the description!';
}

if (empty($add_errors)) { // If everything's OK.
//do the insertion
$q = 'INSERT INTO ........')';
}

}//end of form submission


echo '<form action="product_add.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">';
echo '<input type=..... name=...... id=.....>';
echo '<input type=..... name=...... id=.....>';
echo '<input type=..... name=...... id=.....>';
echo '</form';
//this form is only a single row with multiple column(field) ,I am trying to make it into multiple column

1 个答案:

答案 0 :(得分:1)

我会重写上面的代码......我将在这里重写它:

<?php
$rows = 10; // rows desired.

//if there is a post request
if ($_SERVER['REQUEST_METHOD'] == 'POST') { 

    while($i < $rows){
        if (empty($_POST['description'.$i])) {
        $add_errors['description'.$i] = 'Please enter the description!';
        }
        // more error checking if needed...
        ++$i;
    }

    if (empty($add_errors)) { // If everything's OK.
        //do the insertion
        $q = 'INSERT INTO ........')';
    }

}//end of form submission

echo '<form action="product_add.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">';
$i = 0;
while($i < $rows){
    echo '<input type=..... name="description'.$i.'" id=.....>';
    ++$i;
}
echo '</form';
?>

尝试类似的东西...(我的代码可能有一两个错误,因为我刚刚在这里写了它并没有测试它)但这是一般的想法。 =)