简体   繁体   中英

how to insert multiple rows to mysql

i am trying for ages but can not get this working.

So far this is working perfect

<?
                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>

My question is how can i add another 5 sets of start and end inputs to this code?

I know i can just add another input names, if statements and change their names but i want to learn the proper way.

You use an array.

So how to use an array? In HTML, you need this:

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"  />

And in PHP you need this:

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);

}

I didn't use your table structure in this example, but I think it's simple enough so that you can learn and modify it.

Don't ever insert values in your Database without escaping them!

The proper way of doing this would be:

  1. Add your Fields or whatever to your HTML-Form.
  2. Use the MySQLi-class in PHP to access your Database (it's Object Oriented).
  3. Create a PreparedStatement for your Insert
  4. Loop over your given Fields and bind the parameters to your PreparedStatement
  5. Execute the Statement
  6. Close the Database Connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM