How to use multiselect value in php

3

I'm getting a value from a multiselect and sending it via ajax:

Assuming the value of the multiselect to be:

["1","2","3"]  // é esse valor que está sendo enviado (value do multiselect)

After rescuing this value in the php file that you received from ajax, how could I give an explode in this value just to get the numbers?

    
asked by anonymous 06.12.2015 / 17:38

3 answers

1

Well, after doing some tests I noticed that it had a value that was getting the wrong bit.

Sergio's comment helped a lot, so

$arr = json_decode('["1","2","3"]');

is valid. In this case, I was able to get the array directly the way it was coming from ajax too

then:

$array = $_POST['array'] // recebida via ajax

foreach($array as $valor){
      $query = "INSERT INTO table (col1, col2) VALUES ('$valor', '1')"; 
      $resultado = mysqli_query($conexao->abrirConexao(), $query);
    }

It also worked correctly!

What it's worth is to test, break the head, that one hour ends up achieving!

    
06.12.2015 / 20:07
1

If this value is a string, replace it with the unwanted characters, then with a valid one, it will convert the string into an array.

<?php

$valor = '"["1","2","3"]"';
$str = str_replace(array('"','[', ']'), '', $valor);
$itens = explode(',', $str);

echo '<pre>';
print_r($itens);
    
06.12.2015 / 17:45
1

The correct answer depends on how you sent the data via ajax, whether it was through the POST, GET or PUT method ... But assuming you sent via POST, the received data apparently is an array, in this case, it would look something like this:

/**
   'data' é a variável que você
   definiu no método do ajax,
   se vc não definiu, basta
   capturar $dados = $_POST;
**/ 
   $dados = $_POST['data'];

  $numeroUm   = $dados[0];
  $numeroDois = $dados[1];
  $numeroTres = $dados[2];

 echo $numeroUm.'<br>' .
      $numeroDois.'<br>' .
      $numeroTres.'<br>';
      die();
    
08.12.2015 / 12:47