Question:
I have the following HTML form:
<h2>Sessao 1</h2>
<input type="text" name="ipl[]" class="span12 ">
<input type="text" name="spot[]" class="span12 ">
<input type="text" name="energia[]" class="span12 ">
<input type="text" name="dcd[]" class="span12 ">
<input type="text" name="dis_inicial[]" class="span12 ">
<input type="text" name="dis_final[]" class="span12 ">
<h2>Sessao 2</h2>
<input type="text" name="ipl[]" class="span12 ">
<input type="text" name="spot[]" class="span12 ">
<input type="text" name="energia[]" class="span12 ">
<input type="text" name="dcd[]" class="span12 ">
<input type="text" name="dis_inicial[]" class="span12 ">
<input type="text" name="dis_final[]" class="span12 ">
<h2>Sessao [....]</h2>
<input type="text" name="ipl[]" class="span12 ">
<input type="text" name="spot[]" class="span12 ">
<input type="text" name="energia[]" class="span12 ">
<input type="text" name="dcd[]" class="span12 ">
<input type="text" name="dis_inicial[]" class="span12 ">
<input type="text" name="dis_final[]" class="span12 ">
<h2>Sessao 200</h2>
<input type="text" name="ipl[]" class="span12 ">
<input type="text" name="spot[]" class="span12 ">
<input type="text" name="energia[]" class="span12 ">
<input type="text" name="dcd[]" class="span12 ">
<input type="text" name="dis_inicial[]" class="span12 ">
<input type="text" name="dis_final[]" class="span12 ">
When submitting I would like to include each session in a new line in the MySQL database. In other words, I need a "foreach", "loop", "while" in PHP to separate the sessions and insert each one.
Answer:
This is the scope for multiple inserts in MySQL:
INSERT INTO NOME_DA_TABELA (COLUNA1,COLUNA2,COLUNA3) VALUES
(VALOR1,VALOR2,VALOR3),
(VALOR4,VALOR5,VALOR6),
(VALOR7,VALOR8,VALOR9);
In PHP, iterate the received array: *I assume you are using POST method:
$sql = "INSERT INTO NOME_DA_TABELA (ipl,spot,energia) VALUES";
$data = $_POST;
foreach( $data['ipl'] as $k => $v ){
$sql .= PHP_EOL . "('" . $v . "','" . $data['spot'][$k] . "','" . $data['energia'][$k] . "')";
if( $k > 0 ){
$sql .= ",";
}
}
$sql .= ";";
// Query:
echo $sql; exit;
obs: I just put an example with 3 columns. The rest you can do yourself once you understand the logic. There are other ways to solve it and obviously you need to do the treatments when receiving the data before assembling the SQL query. As these other details are not the main focus of the question, I chose not to comment on them to avoid a long and complicated answer.
See the MySQL manual (5.5): http://dev.mysql.com/doc/refman/5.5/en/insert.html