Insert array into a database using PHP

1

In the site I'm creating I have a form where people can add multiple topics. My problem is when a second or more topics are created because only the first one goes to the bank and I can not get the others 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>";
}
    
asked by anonymous 09.06.2018 / 20:48

2 answers

2

The problems found in your code are:

  • Wrong $nm_topico = $_POST['campo[]'];

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

  • The values of the INSERT statement ('$nm_reuniao','$dt_reuniao', '$logado')" ;

    Instead of $logado I think it should be $nm_topico

  • But even being $nm_topico would only insert one row in the table

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

      

    A single INSERT ... VALUES statement can add multiple records to a table if you supply 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 declaration shown creates three records in the People table, assigning the listed values to the nome and sobrenome columns of each record. The id column is not listed explicitly, so MySQL assigns a string value to that column in each record.

    A multi-line INSERT statement is logically equivalent to a set of individual single-line declarations. However, multi-line declaration is more efficient because the server can process all lines at once rather than in separate operations. When you have many records to add, multi-line claims 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 convey information to the server (this size is controlled by the max_allowed_packet variable, 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 indicated below, I do not know, your question is not clear enough

    $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";
    
        
    10.06.2018 / 03:05
    1

    Do as follows:

    $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);
    }
    

    Your $nm_topico variable receives an array with the information passed by your form with name='campo[]' , so all lines need to be repeated by inserting row by line.

        
    09.06.2018 / 21:53