Insert multiple mysql checkbox records

Asked

Viewed 391 times

2

are trying to enter in the database information of multiple checkbox at once , for example a news is related to more than one category then and only select the categories and save , however this giving this error ,

Notice: Array to string conversion in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 19
ErroArray ( [0] => HY000 [1] => 1366 [2] => Incorrect integer value: 'Array' for column 'carteira_id' at row 1 ) 
Notice: Undefined variable: idlogado in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 32

Notice: Array to string conversion in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 19
ErroArray ( [0] => HY000 [1] => 1366 [2] => Incorrect integer value: 'Array' for column 'carteira_id' at row 1 ) 
Notice: Undefined variable: idlogado in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 32

Notice: Array to string conversion in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 19
ErroArray ( [0] => HY000 [1] => 1366 [2] => Incorrect integer value: 'Array' for column 'carteira_id' at row 1 ) 
Notice: Undefined variable: idlogado in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 32

Notice: Array to string conversion in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 19
ErroArray ( [0] => HY000 [1] => 1366 [2] => Incorrect integer value: 'Array' for column 'carteira_id' at row 1 ) 
Notice: Undefined variable: idlogado in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 32

Notice: Array to string conversion in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 19
ErroArray ( [0] => HY000 [1] => 1366 [2] => Incorrect integer value: 'Array' for column 'carteira_id' at row 1 ) 
Notice: Undefined variable: idlogado in C:\Program Files\VertrigoServ\www\painel\pg\cadamsg.php on line 32

several errors appeared because there are all checkbox selected there is the code

<?php
                  foreach ($carteira as $cart) {
                     echo '
                    <div class="checkbox i-checks">
                      <label>
                        <input type="checkbox" name="f_carteira[]" value="'.$cart['id'].'">
                        <i></i>
                      '.$cart["nome"].'
                      </label>
                    </div> ' ;
                  }
                        ?>

Insert

<?php
          session_start();
 include '../config/config.inc.php';

        error_reporting(E_ALL);


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


     $carteira = $_POST['f_carteira'];

      if($carteira){
          foreach ($carteira as $car) {
            $cadastrarmensagem = $pdo->prepare("INSERT INTO mensagem(codigo,conteudomsg,categoria_id,carteira_id,usuario_id) VALUES(:codigo,:conteudo,:categoria,:carteira,:usuarioid)");
      $cadastrarmensagem->bindValue(":codigo",$_POST["f_codigo"]);
      $cadastrarmensagem->bindValue(":conteudo",$_POST["f_msg"]);
      $cadastrarmensagem->bindValue(":categoria",$_POST["f_cat"]);
      $cadastrarmensagem->bindValue(":carteira",$_POST["f_carteira"]);
      $cadastrarmensagem->bindValue(":usuarioid",$_POST["f_usuario"]);
      $cadastrarmensagem->execute();
      $linha = $cadastrarmensagem->rowCount();
      if($linha > 0){
         echo "Mensagem Cadastrada com Sucesso";

         header ("Location: ../index.php?pg=mensagens");
      }else {
        echo "Erro";
        //imprimindo erro da variavel de consulta
       print_r($cadastrarmensagem->errorInfo());

        echo "$idlogado";
      }
          }
      }

    }else{echo "aconteceu algum erro";}
 ?>

3 answers

3

When you do <input type="checkbox" name="f_carteira[]" what comes POST is an array and the conversion from array to string is the word Array. What you can do is give one implode to convert to a string with categories.

$aCategoria = ['1','2','3'];
$sCategorias = implode(",",$aCategoria);
//resultando em 1,2,3

But as the mistake is Incorrect integer value, and you want to save several categories, maybe it is better to use another table to store the categories, where you save the id of the item and id of the categories for each of the item categories.

  • hello friend , could inform me how I would create a new table ?

2

As quoted by our companion Fernando, an implode can solve your problem, making everything turn into a string and then you will be able to insert.

This would work perfectly, but particularly, I prefer to use JSON rather than a comma string. In your case the two would work, however, if one of the array values were another array, it would not work with only one implode.

Example with JSON:

<?php 
$bolso = array('seda', 'bic', 'green');
$json = json_encode($bolso);
// $json é igual a uma string: ["seda", "bic", "green"]

Then you can work with the data again as follows:

<?php
$json = '["seda", "bic", "green"]';
$bolso = json_decode($json, true);
//bolso é igual a um array: array('seda', 'bic', 'green')

It is important to remember that if the second json_decode() argument is not true, instead of returning an array to you, it will return an object (da para trabalhar similarly in many ways, but for example, a foreach would not work if it were an object).

  • could show me a practical example for my problem ?

  • 1

    Well remembered Ryzinho, if it is an array array would not work with implode, JSON a good solution too, I’ve used in some cases, the only problem worth looking at is if we use this column as filter in the queries, I’ve had problems with it. So suggest using another table.

  • Well noted Fernando. There below in Thalles' answer he put the following: $wallet = $_POST['f_wallet']; $jsoncart = json_encode($wallet); This gave the foreach error because $jsoncart is in this case an object, not an array. Use: $jsoncart = json_encode($wallet, true); to create a json array.

-1

Good people , none of the situations worked out I tried with json doing so

 $carteira = $_POST['f_carteira'];
 $jsoncart = json_encode($carteira);

returned that error :

Invalid argument supplied for foreach()

and with implode

 $carteira = $_POST['f_carteira'];
 $scarteira = implode(",",$carteira);

Invalid argument supplied for foreach()

  • ok friend , unfortunately I have no full knowledge of the tool ,

  • I notice. But knowledge comes with practice, so paying attention to the tips, you get the hang of it. Experiment with json_decode instead of Encode. My suggestion, if you cannot solve with Code is to open a separate question and paste the complete code and delete this new question of yours, leaving as it was (the original question and the answers already given). PS: If the accepted answer was good, and it was you who changed the code, you can let it accept as it was (because it was not the fault of those who answered that there was a new situation in the code)

Browser other questions tagged

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