How to save the data of a Multiple SELECT in a single field of my Database?

0

I have a multiple select and when I save the data in my database it does it separately, and I want it to save the selected data in a single field. How can I do it?

  

<select  multiple="multiple" size="7"  name="dias[]">
  <option value="Lunes">Lunes</option>
  <option value="Martes">Martes</option>
  <option value="Miercoles">Miercoles</option>
  <option value="Jueves">Jueves</option>
  <option value="Viernes">Viernes</option>
  <option value="Sabado">Sabado</option>
  <option value="Domingo">Domingo</option>
</select>

$dias = $_POST["dias"];

foreach($dias as $valor){


$sql ="INSERT INTO tabla (dias) VALUES ('$valor')"; 

$resultado = mysqli_query ($mysqli, $sql);

if (!$resultado){

  alert("FALLO EL REGISTRO DE HORARIO");

}

else{

  alert("REGISTRO DE HORARIO CON EXITO");

}


}mysqli_close($mysqli);

?>
    
asked by Araceli 09.08.2017 в 00:56
source

1 answer

1

Good morning,

One solution I can think of is that you save a json from the array you receive as a result:

$dias = $_POST["dias"];
$json = json_encode($dias, true);
$sql =sprintf("INSERT INTO tabla (dias) VALUES ('%s')", $json);
$resultado = mysqli_query ($mysqli, $sql);
if (!$resultado){
    alert("FALLO EL REGISTRO DE HORARIO");
} else {
    alert("REGISTRO DE HORARIO CON EXITO");
}
mysqli_close($mysqli);

With this you would save a json of the days that you have been selected, and then when you have to read it, you decode that field with json_decode .

Note: Since you use the $_POST variable directly, you may have SQL injection problems. Check the security of your code.

    
answered by 09.08.2017 в 01:06