1

i have form as below with same name text field columns, i want to insert multiple arrays data to mysql using this below form. pls tell me how to do this using foreach in php mysql

First Column

<input  name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />

Second Column

<input  name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
1
  • 2
    Please show us what you have tried so far Commented Apr 25, 2013 at 5:12

2 Answers 2

2

First of all I would rename your form fields to make this easier:

<?php
$number_of_columns = 2;
for($i=0;$i<$number_of_columns;$i++) :?>
    <input  name="col[<?=$i?>][date]" type="text" class="datepicker">
    <input type="text" name="col[<?=$i?>][local]" />
    <input type="text" name="col[<?=$i?>][desc]" />
    <input type="text" name="col[<?=$i?>][ta]" />
    <input type="text" name="col[<?=$i?>][car]" />
<?php endfor;?>

And then once you get the data, you can just loop through the $_POST['col'] array and insert each one individually into the database. I'm assuming here that you've already connected to your database and are using the mysql library.

$cols = $_POST['col'];
$table = 'table_name';
foreach($cols as $col) {
    $local = mysql_real_escape_string($col['local']);
    $desc = mysql_real_escape_string($col['desc']);
    $ta = mysql_real_escape_string($col['ta']);
    $car = mysql_real_escape_string($col['car']);
    mysql_query("INSERT INTO `{$table}` (`local`, `desc`, `ta`, `car`) VALUES('{$local}', '{$desc}', '{$ta}', '{$car}')") or die(mysql_error());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You jraede it is working great. i am searching for two days for this. thank you.
0

Try this code:

extract($_POST);
$n = count($date);
for ($i = 0; $i < n; $i++) {
    $query = 'INSERT INTO `table` (`c1`, `c2`, `c3`, `c4`, `c5`) VALUES (\'' . $date[$i] . '\', \'' . $local[$i] . '\', \'' . $desc[$i] . '\', \'' . $ta[$i] . '\', \'' . $car[$i] . '\')';
    // Here you must execute your query
}

2 Comments

Thank You Michael It is Working fine.
Hai Michael can help me. Code working but inserting some blank rows in mysql table, because if we didn't type values in some rows in form.

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.