如何向mysql插入多行

时间:2011-05-12 16:05:43

标签: php mysql

我正在尝试多年但却无法使其发挥作用。

到目前为止,这是完美的

<?
                if ($_POST['newhour_start']!=""&&$_POST['newhour_end']!="") 
                {
                    $inserthour = mysql_query("INSERT INTO hour 
                    (hour_start,hour_end,hour_day) VALUES 
                    ('".$_POST['newhour_start']."','".$_POST['newhour_end']."','".$_POST['newhour_day']."')");
                }

?>
    <td colspan="5">
        Start:<input name="newhour_start" type="text" id="newhour_start" > 
        End: <input name="newhour_end" type="text" id="newhour_end" >
        <input name="newhour_day" type="hidden" id="newhour_day" value="Monday" >
    </td>

我的问题是如何在此代码中添加另外5组开始和结束输入?

我知道我可以添加另一个输入名称,if语句并更改其名称,但我想学习正确的方法。

2 个答案:

答案 0 :(得分:2)

您使用数组。

那么如何使用数组呢?在HTML中,您需要:

Start #1:<input name="newhour_start[]" type="text" /> 
End #1: <input name="newhour_end[]" type="text"  />

Start #2:<input name="newhour_start[]" type="text" /> 
End #2: <input name="newhour_end[]" type="text"  />

Start #3:<input name="newhour_start[]" type="text" /> 
End #3: <input name="newhour_end[]" type="text"  />

在PHP中你需要这个:

if(isset($_POST['newhour_start']) && isset($_POST['newhour_end']))
{
    foreach($_POST['newhour_start'] as $index => $start)
    {
        $hour_start = $start; // now this is the fun part - you CLEAN this string to avoid SQL injection
        $hour_end = $_POST['newhour_end'][$index]; // clean this one too

        $insert[] = "('$hour_start', '$hour_end')";
    }

    $query = "INSERT INTO table (first_column, secon_column) VALUES ". implode(',', $insert);

}

在这个例子中我没有使用你的表结构,但我认为这很简单,你可以学习和修改它。

答案 1 :(得分:0)

不要在数据库中插入值而不转义它们!

这样做的正确方法是:

  1. 添加您的字段或其他任何内容 HTML表格。
  2. 使用PHP中的MySQLi-class 访问您的数据库(它的对象 取向)。
  3. 为您创建PreparedStatement 插入
  4. 遍历给定的字段并绑定 你的参数 PreparedStatement的
  5. 执行声明
  6. Close the Database连接。
相关问题