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:
- Add your Fields or whatever to your HTML-Form.
- Use the MySQLi-class in PHP to access your Database (it's Object Oriented).
- Create a PreparedStatement for your Insert
- Loop over your given Fields and bind the parameters to your PreparedStatement
- Execute the Statement
- Close the Database Connection.
精彩评论