0

我有一个表单,用户可以根据需要在其中添加更多字段...

他可以添加 1,2,3,.. 行的字段..

我使用的代码在这里,

<?php
echo '
<form method="post" action="">
   <input type="hidden" name="mod" value="'.$mod.'" />
   <table style="width: 700px">
   <tr>
       <th>Description</th>
       <th>Quantity</th>
       <th>Price</th>
   </tr>';

// Loop to prepare the display of 100 product lines
for ($i=0; $i<100; $i++) {

   if ($text['quantity'][$i] == "") $text['quantity'][$i] = 1;
   if ($text['unit'][$i] == "") $text['unit'][$i] = "0.00";
   // Display only the first line
   if ($nbr_ligne == 0) $nbr_ligne = 1;
   if ($i >= $nbr_ligne) $display = 'style="display:none"';
   echo '
   <tr id="cell'.$i.'" '.$display.'>
       <td>
           <textarea name="text[detail]['.$i.']">'.stripslashes($text['detail'][$i]).'</textarea>
           <br />
           <a href="javascript:void(0)" onclick="javascript:document.getElementById(\'cell'.($i+1).'\').style.display=\'table-row\'; this.style.display=\'none\'">[+]</a>
       </td>
       <td>
           <input name="text[quantity]['.$i.']" id="q'.$i.'" value="" size="4" />
       </td>
       <td>
           <input name="text[unit]['.$i.']" id="u'.$i.'" value="" size="7" /> USD
       </td>
   </tr>';
}

echo '
   </table>
   <input type="submit" name="save" value="Save" />
</form>
';
?>

字段添加成功。

现在我想将这些字段的值存储在数据库中。

我用于此的代码是:

if(isset($_POST['save']))
{
    echo mysql_error($db);


       extract($_POST);
       $insert=mysql_query(" insert into add (description, quantity, price) values ('{$text['detail'][$i]}','{$text['quantity'][$i]}','{$text['unit'][$i]}')") or die("unable to insert"); 
}

但它不起作用。请帮帮我。我非常需要它。

4

2 回答 2

0

如果 $i 等于添加的行的 nr,则需要将 mysql 查询放入循环中:

if(isset($_POST['save']))
{
for ($e = 1; $e <= $i; $e++) {
$insert=mysql_query(" insert into add (description, quantity, price) values ('".$text['detail'][$e]."','".$text['quantity'][$e]."','".$text['unit'][$e]."')") or die("unable to insert"); 
}
}
于 2012-09-24T11:04:10.257 回答
0

这里的问题是 $i 尚未在您用于保存到数据库的脚本中初始化。如果数字不存在,您将需要从 0 循环到 100 和 BREAK。您还使用了保留关键字add。在保留关键字上使用反引号`。

extract($_POST);

foreach(range(0,100) as $i){
    if(isset($text['detail'][$i]) && isset(isset($text['quantity'][$i]) && isset(isset($text['unit'][$i])){
         $insert= mysql_query(" INSERT INTO `add` (`description`, `quantity`, `price`) VALUES ('".$text['detail'][$i]."','".$text['quantity'][$i]."','".$text['unit'][$i]."')") or die(mysql_error());
    }
    else{
        break;
    }
}

不太喜欢循环插入的方式,但上面的代码应该可以工作,即使它显然不是最好的解决方案。更好的方法是创建一个插入多行的单一 INSERT 查询:

INSERT INTO example (name, age)
VALUES   ('John', 24),   ('Katrina', 21),   ('Michael', 22),   ('Hui Ling', 25),   ('Catherine', 29)

如果您必须对单独的查询进行循环,出于性能原因,您应该使用准备好的语句。

其他问题:

  1. 您对SQL 注入持开放态度。
  2. 您正在使用不再推荐的 mysql 函数。请改用 PDO 或 mysqli。
于 2012-09-24T11:08:16.607 回答