Jump to content

Inserting loops into a table


rvinikof

Recommended Posts

I have a loop that creates the option to enter more than one book, author ect., where $q is just the number they enter that determines how many times the text boxes show up.

 

for($i=0; $i < $q; $i++)

{

 

echo '<b>Book author:</b> <input type = "text" name = "bookauthor"/>';

 

echo '<b>Book title:</b> <input type = "text" name = "booktitle"/>';

 

echo '<b>Book edition:</b> <input type = "text" name = "edition"/>';

 

echo '<b>ISBN:</b> <input type = "text" name = "isbn"/>';

 

echo '<b>Required or Optional?</b> <select name = "reqoropt">';

echo '<option value = "required">Required</option><option value = "optional">Optional</option></select>';

 

 

}

 

How do I then update this into my table? Before this is updated, I will have a requestID and a courseID that is inserted $q times. I want to have each author, title, ect. be inserted into a different requestID.

Link to comment
https://forums.phpfreaks.com/topic/60975-inserting-loops-into-a-table/
Share on other sites

Add "[]" to field names so data is posted in array

<?php
for($i=0; $i < $q; $i++)
         {
            
            echo 'Book author: <input type = "text" name = "bookauthor[]"/>';
         
            echo 'Book title: <input type = "text" name = "booktitle[]"/>';
            
            echo 'Book edition: <input type = "text" name = "edition[]"/>';

            echo 'ISBN: <input type = "text" name = "isbn[]"/>';

            echo 'Required or Optional? <select name = "reqoropt[]">';
            echo '<option value = "required">Required</option><option value = "optional">Optional</option></select>';
      

         }
?>

 

to process

<?php
foreach ($_POST['bookauthor'] as $k => $bookauthor)
{
    $booktitle = $_POST['booktitle'][$k];
    $edition = $_POST['edition'][$k]; 
    $isbn = $_POST['isbn'][$k];
    $reqoropt = $_POST['reqoropt'][$k];
    
    $sql = "INSERT INTO tablename (bookauthor,booktitle,edition,isbn,reqoropt)
            VALUES ('$bookauthor','$booktitle','$edition','$isbn','$reqoropt')"; 
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.