0

I have randomly generated questions and decided to put those in a temporary table. Now, it is already in my html table:

echo "<form action=# method=post>";
echo "<table>";
do{
echo "<tr>";
echo "<td>"."<input type=text value='$rows[question]' name=question>"."</td>;
echo "<td>"."<input type=text value='$rows[correct]' name=correct>"."</td>;
}while($rows=mysqli_fetch_array($rs));
echo "</table>";


echo "<input type=submit name=insert>";

echo "</form>";
?>
</body>
</html>

What I want to happen is, when I hit the insert button name="insert", data from that table, [from row 1 till the last row] will be inserted to my database "tbl_randomq". Is it possible to insert multiple row data simultaneously to database with just 1 click.

I've tried to use while loop, but it only inserts repeated(10times) data coming from the last row. Help with this please :-)

2
  • You can save table data in an array and use them whenever you want. That's the best way. Commented Sep 18, 2014 at 19:37
  • Sir @Sky, will you show it please... Commented Sep 18, 2014 at 19:39

1 Answer 1

1
do{
?>
<tr>
    <td><input type=text value='<?=$row["question"]?>' name='question[]'></td>
    <td><input type=text value='<?=$row["correct"]?>' name='correct[]'></td>    
</tr>
<?php
}while($row = mysqli_fetch_array($rs));

Then to save this :

for ($i=0; $i<count($_POST['question']); $i++){
    $question = addslashes($_POST['question'][$i]);
    $correct = addslashes($_POST['correct'][$i]);
    mysqli_query("
                      insert into tbl_ramdomq (question, correct) 
                      values ('$question','$correct')
    "); 
}

Replace code formatting with your own as you wish. Though for myself I prefer to use short php tags inside html rather than echo because of syntax coloring and better clarity.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you sir! I will try your answer. Will it be like, from my database:tbl_question TO html form table then TO database:tbl_randomq?
I'm not sure how you did your data structure, but here you have 'question' and 'correct' in the loop, so do whatever you need to with them. If you need to pass an id, you can add it in your form as an hidden field.
Okay sir! Thanks! That for loop would be placed after my insert query, right? Thank you very much sir! GodBless you :-)
No, you should place your insert query INTO the loop. So you can insert the values of $question and $correct which change at everyloop to whatever values they had in the table. see?
$sql2="insert into tbl_ramdomq (question, correct) values ('$_POST[question]','$_POST[correct]');"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.