Anuveester Anuveester - 2 months ago 25
HTML Question

How to insert multiple data of same name from single form in multiple row of same column of table

I have

<form action="entry.php" method="post" >
<table>
<tr>
<td>
<input type="text" name="searchid[]" id="searchid" placeholder="Data 1" ><br />
<input type="text" name="searchid[]" id="searchid" placeholder="Data 2" ><br />
<input type="text" name="searchid[]" id="searchid" placeholder="Data 3" ><br />
<input type="text" name="searchid[]" id="searchid" placeholder="Data 4" ><br />
</td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit" value="submit" /></td>
</tr>

</table>
</form>


And entry.php code,

<?php
include "db.php";

if (isset($_POST["submit"]))

$data1 = mysql_real_escape_string($_POST['searchid']);

$query1 = "INSERT INTO php_test (name) VALUES ('$data1')";
$query = mysql_query($query1,$connection);

if($query){
header ("location: index.php");
}
else{
echo "Something Wrong";
}

?>


This code working with single input data but,
I want to enter four data in seperate field of same column and when I submit then it insert data in seperate row, fields name are same and

Answer

$_POST['searchid'] is an array, not a single string. You need to loop over them:

if (isset($_POST["submit"]))
    foreach ($_POST['searchid'] as $searchid) {
        $data1 = mysql_real_escape_string($searchid);
        mysql_query("INSERT INTO php_test (name) VALUES ('$data1')") or die(mysql_error());
    }
}
header("location: index.php");

Also, get rid of the duplicate id="searchid" attributes in your HTML. IDs have to be unique. You probably don't need these elements to have IDs at all.

If you have multiple columns, you can do it like this:

if (isset($_POST["submit"]))
    foreach ($_POST['searchid'] as $index => $searchid) {
        $data1 = mysql_real_escape_string($searchid);
        $data2 = mysql_real_escape_string($_POST['searchid2'][$index]);
        mysql_query("INSERT INTO php_test (name, name2) VALUES ('$data1', '$data2')") or die(mysql_error());
    }
}