Insert array into a database using PHP

Asked

Viewed 567 times

1

On the site I’m creating I have a form where people can add various topics. My problem is at the moment where a second or more topics is created because only the first one goes to the bank and I can’t get the others to be inserted.

The code I’m doing is this one:

<div class="input-field col s10 ">
<input id="topico" type="text" name="campo[]" class="validate" required  >
<label for="topico" class="black-text text-black">Adicione pelo menos um tópico</label>
</div>
<!--BOTAO PARA ADICIONAR MAIS TOPICOS -->
    <a class="btn-floating btn- green" onClick="addCampos()" >
    <i class="material-icons">add</i>
    </a>
    </div>  
    <!--SCRIPT PARA ADIÇÃO DE TOPICOS DE REUNIAO-->
    <script>
      var qtdeCampos = 1;
      function addCampos() {
        var objPai = document.getElementById("campoPai");
//Criando o elemento DIV;
var objFilho = document.createElement("div");
//Definindo atributos ao objFilho:
objFilho.setAttribute("id","filho"+qtdeCampos);

//Inserindo o elemento no pai:
objPai.appendChild(objFilho);
//Escrevendo algo no filho recém-criado:
document.getElementById("filho"+qtdeCampos).innerHTML = "<table><tr><td><div align='right'><input type='text' id='curso"+qtdeCampos+
"' name='campo[]'></div></td> <td><div align='left'<a class='btn-floating btn- light red' onclick='removerCampo("+qtdeCampos+")' value='Apagar campo'><i class='material-icons'>remove</i></a></div></td></tr></table></div></div>";
qtdeCampos++;
}

function removerCampo(id) {
var objPai = document.getElementById("campoPai");
var objFilho = document.getElementById("filho"+id);

//Removendo o DIV com id específico do nó-pai:
var removido = objPai.removeChild(objFilho);
}
</script>

<div id="campoPai"></div>

PHP:

$nm_reuniao = $_POST['nm_reuniao'];
$dt_reuniao = $_POST['dt_reuniao'];
$nm_topico = $_POST['campo[]'];
$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador) VALUES ('$nm_reuniao','$dt_reuniao', '$logado')";

$insert = mysql_query($query,$connect);

if($insert){
  echo"<script language='javascript' type='text/javascript'>alert('Reuniao cadastrado com sucesso!');window.location.href='pagina site.php'</script>";
}else{
  echo"<script language='javascript' type='text/javascript'>alert('Não foi possível cadastrar esse usuário');window.location.href='pagina site.php'</script>";
}
  • If any answer solves your problem mark it as accepted, see https://i.stack.Imgur.com/evLUR.png and because https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-accepta reply/1079#1079.

2 answers

2

The problems found in your code are:

  1. Wrong $nm_topico = $_POST['campo[]'];

    Correct $nm_topico = $_POST['campo'];

  2. The values of the INSERT declaration ('$nm_reuniao','$dt_reuniao', '$logado')";

    Instead of $logado I think it should be $nm_topico

  3. But even though $nm_topico would insert only one row in the table

Forget these fixes that the proposed solution will not use them.

A single statement INSERT ... VALUES can add multiple records to a table if you provide multiple lists of values. To do this, provide a list of values in parentheses for each record and separate the lists with commas.

For example:

INSERT INTO PESSOAS (nome, sobrenome)
VALUES ('Paula','Cavalcante'),('Leo','Caracciolo'),('dvd','SemSobrenome')

The displayed statement creates three records in the persons table, assigning to the columns nome and sobrenome of each record the values listed. The column id is not explicitly listed, so Mysql assigns a sequence value to that column in each record.

A multiple-line INSERT declaration is logically equivalent to a set of individual single-line statements. However, the multiple line declaration is more efficient because the server can process all lines at once instead of in separate operations. When you have many records to add, multi-line statements provide better performance and reduce server load. On the other hand, such statements are more likely to reach the maximum size of the communication buffer used to transmit information to the server (this size is controlled by the variable max_allowed_packet, which has a default value of 1MB).

PHP code

$nm_reuniao = $_POST['nm_reuniao'];
$dt_reuniao = $_POST['dt_reuniao'];

//Use o foreach para gerar a lista de valores
foreach($_POST['campo'] AS $indice => $valor) {
  $values .= " ('$nm_reuniao', '$dt_reuniao', '$valor'),";
}
//retira a ultima virgula
$values=substr($values, 0, -1);

$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador`) VALUES $values";

$insert = mysql_query($query,$connect);

Maybe it was as below indicated, I do not know, your question is not quite clear

$values .= " ('$nm_reuniao', '$dt_reuniao','$logado','$valor'),";

$values=substr($values, 0, -1);

$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador,nm_topico) VALUES $values";

1

Do it this way:

$topicos = $_POST['campo'];
$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador,nm_topico) VALUES ('$nm_reuniao','$dt_reuniao', '$logado','$nm_topico')";
foreach ($topicos as $nm_topico) {
  $insert = mysql_query($query,$connect);
}

Its variable $nm_topico receives an array of the information passed by your form with name='campo[]', then in order to insert all lines it is necessary to make a repeat structure by inserting line by line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.