Wednesday, November 12, 2014

How to Post Data into Table with Same Name Multiple Rows

There are many PHP queries and its solutions available on the Internet. Here, I would like to discuss about one of them. You will get a solution about to post data into a table with same name multiple rows. Here, is the one example given to be understand. There is one code below with lots of input and same name.

<input type = "text" name = "point[]" />
<input type = "text" name = "point[]" />
<input type = "text" name = "comment[]" />
<input type = "text" name = "comment[]" />
<input type = "text" name = "poster[]" />
<input type = "text" name = "poster[]" />
<input type = "text" name = "poster[]" />

All of the above are need to be inserted into one mysql table having id => auto increment, point, comment, poster

Get the Solution below :- 

HTML Code :-

<form method="post" action="checks.php">

    <div id="answer">
        <p> Question 1: ........................ </p>
        <input type="text" name="answer[]" />
        <input type="checkbox" name="yesno[]" value="1" />
        <input type="hidden" name="question_id[]" value="1" />
    </div>
    <div id="answer">
        <p> Question 2: ........................ </p>
        <input type="text" name="answer[]" />
        <input type="checkbox" name="yesno[]" value="2" />
        <input type="hidden" name="question_id[]" value="2" />
    </div>
    <div id="answer">
        <p> Question 3: ........................ </p>
        <input type="text" name="answer[]" />
        <input type="checkbox" name="yesno[]" value="3" />
        <input type="hidden" name="question_id[]" value="3" />
    </div>  
    <input type="hidden" name="product_id" value="x" />
    <input type="submit" />

</form>

checks.php 

<?php

$questions = $_POST["question_id"];
$answers = $_POST["answer"];
$checkbox = $_POST["yesno"];
$product_id = $_POST["product_id"];
$total = 0;

echo "Product ID: ".$product_id."<br />";
foreach ($answers as $a)
{
    $question_id = $questions[$total];
    $checked = (in_array($total, $checkbox)) ? 1 : 0; // 1 = checked

    # Debug
    echo "Question ID: ".$question_id.".<br />";
    $total++;
    echo " Answer ".$total.": ".$a."<br />";
    echo ($checked==1) ? "checked" : "not checked";
    echo "<br />";
    #

    mysql_query("INSERT INTO checked (product_id, question_id, yes_no, comment) VALUES ($product_id, $question_id, $checked, '$a')");
}
?>

0 comments:

Post a Comment